All 15 Java Networking & HTTP Client questions
More in Java Networking & HTTP Client
Advertisement
Back to results for “Communication”
Java › Java Networking & HTTP Client

What is the java.net.Socket and ServerSocket class pair, and how would you implement a basic TCP client-server communication using them at a lower level than HttpClient?

Intermediate

Answer

Socket represents a client-side TCP connection endpoint, and ServerSocket represents a server-side listener that accepts incoming client connections (accept() blocks until a client connects, returning a Socket representing that specific connection) -- both provide raw InputStream/OutputStream access for reading/writing bytes directly over the established TCP connection, representing a much lower-level networking API than HttpClient (which builds an entire HTTP protocol layer on top of raw sockets), appropriate when you need to implement a custom, non-HTTP protocol or need direct low-level control over the TCP connection itself.
// Server
ServerSocket serverSocket = new ServerSocket(8080);
Socket clientSocket = serverSocket.accept();  // blocks until a client connects
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String message = in.readLine();

// Client
Socket socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, server!");
Real-world example A custom, lightweight internal protocol between two in-house microservices (not needing full HTTP semantics) is implemented directly using raw Socket/ServerSocket, avoiding the overhead of a full HTTP request/response cycle for a very simple, high-frequency, low-latency internal communication need.

Common follow-ups: Why would you choose raw sockets over HttpClient or gRPC for a custom protocol, given both provide more built-in structure?;How does this classic blocking Socket API relate to NIO's non-blocking SocketChannel discussed earlier?