Introduction
The java.net package provides classes for writing networked Java programs. Java hides most of the platform-specific networking details, so the same code runs on Windows, Linux, and macOS. This chapter covers basic networking concepts, the Socket and ServerSocket classes for TCP, the DatagramSocket class for UDP, and the URL/URLConnection classes for working with web resources.
Networking Basics
Every host on an IP network has an IP address (32-bit in IPv4, 128-bit in IPv6). A port is a 16-bit number that identifies a specific service on a host — for example, HTTP uses port 80, HTTPS uses 443, SSH uses 22. The combination of IP and port is a socket endpoint. A proxy server is an intermediary that forwards client requests to the destination server; proxies are used for caching, filtering, and anonymity.
java.net Classes and Interfaces
InetAddress— represents an IP address with DNS lookup methodsSocket— TCP client socketServerSocket— TCP server socketDatagramSocket,DatagramPacket— UDP socketsURL,URLConnection— work with URLsHttpURLConnection— HTTP-specific URLConnection
TCP Server Example
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(9000);
System.out.println("Listening on port 9000");
while (true) {
Socket client = server.accept();
new Thread(() -> handle(client)).start();
}
}
static void handle(Socket s) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true)) {
String line;
while ((line = in.readLine()) != null) out.println("echo: " + line);
} catch (IOException e) { e.printStackTrace(); }
}
}TCP Client Example
try (Socket s = new Socket("localhost", 9000);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
out.println("Hello");
System.out.println(in.readLine());
}UDP Datagrams
UDP is connectionless and unreliable but has lower latency than TCP. Use it for applications where occasional packet loss is acceptable — live video, DNS queries, game state updates.
DatagramSocket sock = new DatagramSocket(9999);
byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf, buf.length);
sock.receive(p);
String msg = new String(p.getData(), 0, p.getLength());URL Class
The URL class parses a URL string and provides methods to access its parts — getProtocol(), getHost(), getPort(), getPath(), getQuery(). Call openStream() to open a InputStream to the resource:
URL u = new URL("https://example.com/");
try (BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()))) {
br.lines().forEach(System.out::println);
}InetAddress
InetAddress addr = InetAddress.getByName("google.com");
System.out.println(addr.getHostAddress());Summary
Java networking uses sockets for byte-oriented communication. Socket/ServerSocket implement TCP for reliable connections; DatagramSocket uses UDP for lightweight messaging. The URL family of classes makes HTTP requests trivial. Always close sockets promptly — use try-with-resources.
Important Questions
- Differentiate TCP and UDP.
- What is a port number? List standard ports for HTTP, HTTPS, and SSH.
- Write a TCP echo server in Java.
- Write a TCP client that connects to the echo server.
- Explain the role of
InetAddress. - What are datagrams? Write a UDP sender and receiver.
- How does
URL.openStream()work? Give an example that fetches a web page. - What is a proxy server and what purposes does it serve?