TCP/IP Server Sockets and Datagram (UDP) Programming
TCP/IP Server Sockets
A ServerSocket listens on a port and accepts incoming client connections. Each accepted connection returns a regular Socket used to communicate with that specific client.
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server listening on port 5000...");
while (true) {
Socket clientSocket = serverSocket.accept(); // blocks until a client connects
System.out.println("Client connected: " + clientSocket.getInetAddress());
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message = in.readLine();
System.out.println("Received: " + message);
out.println("Echo: " + message);
clientSocket.close();
}
}
}
Key ServerSocket Methods
| Method | Purpose |
|---|---|
accept() | Blocks until a client connects, returns a Socket |
getLocalPort() | Port the server is bound to |
close() | Stops listening |
setSoTimeout(int ms) | Timeout for accept() |
Concurrent Servers with Threads
A single-threaded server handles one client at a time. Spawning a thread per client allows concurrent connections:
while (true) {
Socket clientSocket = serverSocket.accept();
new Thread(() -> handleClient(clientSocket)).start();
}
Datagram (UDP) Programming
UDP (User Datagram Protocol) is connectionless and unreliable but fast — no handshake, no guaranteed delivery or order. Java represents UDP communication with DatagramSocket and DatagramPacket.
UDP Client
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
byte[] message = "Hello UDP Server".getBytes();
InetAddress serverAddr = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(message, message.length, serverAddr, 6000);
socket.send(packet);
socket.close();
}
}
UDP Server
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6000);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet); // blocks until a packet arrives
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + received + " from " + packet.getAddress());
}
}
}
TCP vs UDP
| Feature | TCP (Socket/ServerSocket) | UDP (DatagramSocket/DatagramPacket) |
|---|---|---|
| Connection | Connection-oriented (3-way handshake) | Connectionless |
| Reliability | Guaranteed delivery, ordered | No guarantee, may lose/reorder packets |
| Speed | Slower (overhead) | Faster (minimal overhead) |
| Use case | Web, email, file transfer | Streaming, gaming, DNS, VoIP |
| Java classes | Socket, ServerSocket | DatagramSocket, DatagramPacket |
Key Takeaway:ServerSocket.accept()blocks until a TCP client connects, and threading lets a server handle many clients concurrently. UDP trades reliability for speed —DatagramSocketsends/receives self-containedDatagramPackets with no connection setup.