TCP/IP Client Sockets, URL, and URLConnection
TCP/IP Client Sockets
A socket is one endpoint of a two-way network connection. Java's Socket class implements a client socket — it connects to a server listening on a host and port.
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws IOException {
// Connect to server at host:port
Socket socket = new Socket("localhost", 5000);
// Output stream: send data to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello Server!");
// Input stream: read the server's reply
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
System.out.println("Server says: " + in.readLine());
socket.close();
}
}
Key Socket Methods
| Method | Purpose |
|---|---|
getInputStream() | Stream to read data from the peer |
getOutputStream() | Stream to send data to the peer |
getInetAddress() | Remote address the socket is connected to |
getPort() / getLocalPort() | Remote / local port number |
close() | Releases the connection |
setSoTimeout(int ms) | Read timeout in milliseconds |
The URL Class
A URL (Uniform Resource Locator) identifies a resource on the Internet. Java's URL class parses and lets you fetch the resource it points to.
import java.net.URL;
public class URLDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com:443/path/page.html?id=1");
System.out.println("Protocol: " + url.getProtocol()); // https
System.out.println("Host: " + url.getHost()); // www.example.com
System.out.println("Port: " + url.getPort()); // 443
System.out.println("File: " + url.getFile()); // /path/page.html?id=1
System.out.println("Path: " + url.getPath()); // /path/page.html
System.out.println("Query: " + url.getQuery()); // id=1
}
}
Reading a URL Directly
import java.io.*;
import java.net.URL;
public class URLReader {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
}
The URLConnection Class
URLConnection gives finer control than openStream() — request headers, response headers, and both reading and writing.
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class URLConnectionDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "JavaClient/1.0");
conn.setDoOutput(false);
conn.connect();
System.out.println("Content-Type: " + conn.getContentType());
System.out.println("Content-Length: " + conn.getContentLength());
System.out.println("Last Modified: " + conn.getLastModified());
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
}
URL vs URLConnection
| Feature | URL | URLConnection |
|---|---|---|
| Simplicity | openStream() — one line to read | More verbose, more control |
| Headers | Not accessible | Request/response headers accessible |
| Writing data | Not supported | Supported via setDoOutput(true) |
| Use case | Quick reads | POST requests, custom headers, metadata |
Key Takeaway:Socketgives a raw TCP client connection for custom protocols.URLandURLConnectionbuild on sockets to fetch web resources — useURL.openStream()for quick reads andURLConnectionwhen you need headers or to send data.