Socket Programming in Java
Socket programming in Java allows direct, low-level communication between machines over TCP or UDP. TCP sockets provide reliable, ordered, bidirectional by...
TCP Sockets: Client and Server
Socket programming in Java allows direct, low-level communication between machines over TCP or UDP. TCP sockets provide reliable, ordered, bidirectional byte streams, making them suitable for protocols where data integrity is required. Java's socket API in java.net maps closely to the Berkeley socket model used in most operating systems.
A TCP server uses ServerSocket to listen for incoming connections on a specific port. Calling accept() blocks until a client connects and returns a Socket representing that connection. The server can then communicate with the client through the socket's input and output streams:
ServerSocket server = new ServerSocket(8080); Socket client = server.accept(); InputStream in = client.getInputStream(); OutputStream out = client.getOutputStream();
A TCP client uses Socket to connect to a server's IP address and port. Once connected, it reads from and writes to the socket's streams just like any other Java IO:
Socket socket = new Socket("localhost", 8080); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer.println("Hello, server"); String response = reader.readLine();
Each accept() call handles one client. A production server spawns a thread for each accepted connection, or better, submits the connection to a thread pool:
ExecutorService pool = Executors.newFixedThreadPool(10); ServerSocket server = new ServerSocket(8080); while (true) { Socket client = server.accept(); pool.submit(() -> handleClient(client)); }
Socket communication is a byte stream; there is no built-in concept of messages or frames. You must define a protocol that tells both sides where one message ends and the next begins. Common approaches include newline-delimited text, length-prefixed binary messages, or using a serialization format.
Always close sockets in finally blocks or use try-with-resources to ensure connections are released. Unclosed sockets hold OS file descriptors, which are a limited resource.
Interview tip: Explain what happens to a server socket when the server process dies. The OS releases all sockets held by the process. If the server is restarted quickly, it may find the port still in TIME_WAIT state from the previous connection. Setting SO_REUSEADDR with serverSocket.setReuseAddress(true) before binding allows reuse of the port in this state.
UDP Sockets and Datagrams
UDP (User Datagram Protocol) is an alternative to TCP for network communication that trades reliability for lower latency and overhead. UDP is connectionless: there is no handshake, no acknowledgment, and no guaranteed ordering. Packets may be lost, duplicated, or arrive out of order. Applications that use UDP must handle these conditions themselves or accept them as acceptable trade-offs.
UDP is appropriate for scenarios where occasional data loss is preferable to the latency of retransmission: live video streaming, online gaming, voice-over-IP, and real-time sensor data. In these cases, a slightly outdated packet is worse than no packet because the application has already moved on to fresher data.
Java's DatagramSocket and DatagramPacket classes implement UDP communication. Unlike TCP, there is no accept() loop; both client and server use DatagramSocket to send and receive packets:
DatagramSocket socket = new DatagramSocket(9090); byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); // blocks until a packet arrives String message = new String(packet.getData(), 0, packet.getLength());
Sending a UDP packet requires specifying the destination address and port in the DatagramPacket:
byte[] data = "Hello".getBytes(); InetAddress dest = InetAddress.getByName("localhost"); DatagramPacket send = new DatagramPacket(data, data.length, dest, 9090); new DatagramSocket().send(send);
DatagramSocket can also be used as a connected socket by calling connect() with a remote address, which restricts sending and receiving to a single remote endpoint. This is useful for client code that always communicates with the same server.
Multicast is a UDP feature that allows a single packet to be received by multiple subscribers who join a multicast group address. Java supports multicast through MulticastSocket. Multicast is used for service discovery protocols, IPTV distribution, and LAN-based peer-to-peer applications.
Interview tip: When asked why you would choose UDP over TCP, give a concrete example such as a real-time game where sending the player's current position every 50ms is more valuable than ensuring every position update is delivered. A slightly stale position received immediately is more useful than a perfectly accurate position received 200ms late due to TCP retransmission.
Non-blocking I/O with NIO
Java's original socket API uses blocking I/O: each read() or accept() call blocks the calling thread until data is available. For servers handling thousands of concurrent connections, dedicating one thread per connection is impractical because threads consume memory and context switching overhead grows with thread count. Java NIO (New I/O), introduced in Java 1.4, provides non-blocking I/O and the Selector API to handle many connections with a small number of threads.
In NIO, channels replace streams. SocketChannel and ServerSocketChannel are the NIO equivalents of Socket and ServerSocket. Channels can be switched to non-blocking mode, where operations return immediately even if no data is available, instead of blocking:
ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.bind(new InetSocketAddress(8080)); serverChannel.configureBlocking(false);
A Selector allows a single thread to monitor multiple channels for readiness. You register channels with the selector for events of interest (accept, read, write). Calling selector.select() blocks until at least one registered channel is ready, then you iterate over the selected keys and handle each ready channel:
Selector selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); for (SelectionKey key : selector.selectedKeys()) { if (key.isAcceptable()) { /* accept new connection */ } if (key.isReadable()) { /* read from channel */ } } selector.selectedKeys().clear(); }
NIO uses ByteBuffer instead of streams for data transfer. ByteBuffer has explicit position and limit pointers that must be managed carefully. Forgetting to call flip() before reading from a buffer that was just written is a common mistake that produces empty reads.
In practice, most developers use Netty, a framework built on top of NIO, rather than using NIO directly. Netty provides a higher-level abstraction over NIO channels and selectors, handles buffer pooling, and provides a pipeline architecture for building network protocols.
Interview tip: Compare the thread-per-connection model to the NIO selector model for a server with 10,000 concurrent clients. The thread-per-connection model requires 10,000 threads consuming roughly 10 GB of stack space. The NIO model can handle all 10,000 connections with a handful of threads, dramatically reducing memory usage and context-switching overhead.