Java Networking Fundamentals: URLs, Sockets, Datagrams, and Network Interfaces
The Java platform provides robust support for network programming through the java.net package, enabling applications to interact with internet resources using high-level abstractions like URLs or low-level constructs such as sockets and datagrams.
Working with URLs
A URL (Uniform Resource Locator) represents a resource on the internet. Java programs can use the URL class to access these resources. The simplest way to create a URL is from a string:
URL site = new URL("https://example.com/");
Relative URLs can also be constructed using a base URL:
URL base = new URL("https://example.com/docs/");
URL page = new URL(base, "tutorial.html");
Once a URL object exists, its components—protocol, host, port, path, query, and fragment—can be extracted using accessor methods like getProtocol(), getHost(), and getPort().
To read content directly from a URL:
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(site.openStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
For more control, open a URLConnection:
URLConnection conn = site.openConnection();
// Set request properties if needed
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
// Read response
}
Writing to a URL (e.g., submitting form data via POST):
connection.setDoOutput(true);
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())) {
writer.write("query=" + URLEncoder.encode("search term", "UTF-8"));
}
Socket-Based Communication
Sockets provide reliable, connection-oriented communication using TCP. A client connects to a server using a Socket, while the server listens with a ServerSocket.
Client example:
try (Socket socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
out.println("Hello");
System.out.println("Server replied: " + in.readLine());
}
Server example:
try (ServerSocket server = new ServerSocket(8080)) {
while (true) {
try (Socket client = server.accept();
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
String input = in.readLine();
out.println("Echo: " + input);
}
}
}
Servers handling multiple clients typically spawn a new thread per connection.
Datagram Communication with UDP
UDP offers connectionless, unreliable messaging via DatagramSocket and DatagramPacket. It’s suitable for applications where speed matters more than guaranteed delivery.
Server sending quotes:
DatagramSocket socket = new DatagramSocket(4445);
byte[] buffer = quote.getBytes();
InetAddress clientAddr = receivedPacket.getAddress();
int clientPort = receivedPacket.getPort();
DatagramPacket reply = new DatagramPacket(buffer, buffer.length, clientAddr, clientPort);
socket.send(reply);
Client requesting a quote:
DatagramSocket socket = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName("localhost");
DatagramPacket request = new DatagramPacket(new byte[1], 1, serverAddr, 4445);
socket.send(request);
byte[] recvBuf = new byte[256];
DatagramPacket response = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(response);
String quote = new String(response.getData(), 0, response.getLength());
For broadcasting to multiple clients, use MulticastSocket and a multicast group address (e.g., 230.0.0.1). Clients join the group to receive messages.
Accessing Network Interface Details
The NetworkInterface class allows inspection of local network interfaces:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface ni : Collections.list(interfaces)) {
System.out.println("Interface: " + ni.getDisplayName());
System.out.println("Up: " + ni.isUp());
System.out.println("Loopback: " + ni.isLoopback());
Enumeration<InetAddress> addresses = ni.getInetAddresses();
for (InetAddress addr : Collections.list(addresses)) {
System.out.println(" Address: " + addr.getHostAddress());
}
}
This is useful for selecting specific interfaces for binding sockets or joining multicast groups.
HTTP Cookie Management
Java supports HTTP state management via cookies using CookieHandler and CookieManager:
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
By default, cookies are accepted only from the originating server (CookiePolicy.ACCEPT_ORIGINAL_SERVER). Custom policies and persistent cookie stores can be implemented by extending CookiePolicy and CookieStore.
Note that network operations in applet are restricted by the security manager, whereas standalone applications have full access unless constrained by system policies.