Java Socket Basics
A Java socket is one end of a two-way connection between two programs over a network. The java.net.Socket class opens a TCP connection to a server, and then you read and write data through ordinary input and output streams, just like reading a file.
Sockets sit underneath almost every network protocol: HTTP, database drivers, mail servers and chat apps all use them. In this lesson you will connect a Java socket to a server, send and receive text, detect a closed connection, set timeouts and socket options, and finally build a reusable client for a small key-value protocol.
How a Java Socket Connection Works
A TCP connection is identified by four values: the client's IP address and port, and the server's IP address and port. The server waits on a known port. The client connects to it, and the operating system gives the client a free ephemeral port for its side.
| Step | Client side (Socket) | Server side (ServerSocket) |
|---|---|---|
| 1 | Listens on a port, for example 8093 | |
| 2 | new Socket("localhost", 8093) connects | accept() returns a new Socket |
| 3 | Writes to getOutputStream() | Reads from its getInputStream() |
| 4 | Reads from getInputStream() | Writes to its getOutputStream() |
| 5 | close() ends the connection | Sees end of stream, closes its socket |
Once connected, both sides are equal: each has a Socket with an input stream and an output stream. TCP guarantees that bytes arrive complete and in order, as described in Java networking basics.
Common Socket method | Purpose |
|---|---|
Socket(host, port) | Create and connect in one step |
connect(SocketAddress, timeout) | Connect with a timeout (after new Socket()) |
getInputStream() / getOutputStream() | Streams for reading and writing bytes |
setSoTimeout(ms) | Maximum time a read may block |
getInetAddress(), getPort() | The remote address and port |
getLocalPort() | The local (ephemeral) port |
shutdownOutput() | Tell the other side you are done sending |
close() | Close the connection and both streams |
A Local Server for the Examples
A socket needs something to connect to. Save this TextServer.java next to the examples. It listens on localhost:8093 and understands one command per line:
| Command | Reply |
|---|---|
HELLO name | Hi name! |
UPPER text | The text in upper case |
SET key value | OK (stores the value) |
GET key | The value, or NOT_FOUND |
SLOW | Waits 2 seconds, then replies |
QUIT | BYE, then closes the connection |
// FILE: TextServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
// A small line-based TCP server on localhost:8093 used by the examples
public class TextServer {
private static final Map<String, String> STORE = new ConcurrentHashMap<>();
public static ServerSocket start() throws IOException {
ServerSocket server = new ServerSocket(8093, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
while (!server.isClosed()) {
try {
Socket client = server.accept();
Thread.ofVirtual().start(() -> handle(client));
} catch (IOException e) {
return; // server was closed
}
}
});
return server;
}
private static void handle(Socket socket) {
try (socket;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8)) {
String line;
while ((line = in.readLine()) != null) {
String[] parts = line.split(" ", 3);
switch (parts[0].toUpperCase()) {
case "HELLO" -> out.println("Hi " + parts[1] + "!");
case "UPPER" -> out.println(line.substring(6).toUpperCase());
case "SET" -> { STORE.put(parts[1], parts[2]); out.println("OK"); }
case "GET" -> out.println(STORE.getOrDefault(parts[1], "NOT_FOUND"));
case "SLOW" -> { Thread.sleep(2000); out.println("finally done"); }
case "QUIT" -> { out.println("BYE"); return; }
default -> out.println("ERROR unknown command: " + parts[0]);
}
}
} catch (IOException | InterruptedException | ArrayIndexOutOfBoundsException e) {
// client went away or sent a bad line; just close the connection
}
}
}
The server uses ServerSocket and a virtual thread per client. You do not need to understand it yet; the next lesson, Java ServerSocket, explains how it works. Here we focus on the client side.
Connecting a Java Socket to a Server
The constructor new Socket(host, port) looks up the host, opens the TCP connection and returns a connected socket. To send text, wrap the output stream in a PrintWriter; to read text, wrap the input stream in a BufferedReader.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class FirstSocket {
public static void main(String[] args) throws Exception {
ServerSocket server = TextServer.start();
// Connect to the server: host name + port number
try (Socket socket = new Socket("localhost", 8093);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
System.out.println("Connected: " + socket.isConnected());
System.out.println("Remote: " + socket.getInetAddress().getHostAddress() + ":" + socket.getPort());
System.out.println("Local port: " + (socket.getLocalPort() > 0 ? "picked by the OS" : "none"));
out.println("HELLO Priya"); // send one line
System.out.println("Server says: " + in.readLine()); // read one line
} finally {
server.close();
}
}
}
Output:
Connected: true
Remote: 127.0.0.1:8093
Local port: picked by the OS
Server says: Hi Priya!
How it works:
new Socket("localhost", 8093)blocks until the connection is open, then returns. If no server is listening, it throwsConnectException.new PrintWriter(stream, true, UTF_8)turns on auto-flush, so everyprintln()is sent at once. Without it, the text could sit in a buffer and the server would wait forever.in.readLine()blocks until a full line (ending in\n) arrives from the server.- The local port is chosen by the operating system and changes on every run, which is why the example only checks that it exists.
- Try-with-resources closes the reader, the writer and the socket. Closing any of the socket's streams also closes the socket.
Note: Always pass a charset such as
StandardCharsets.UTF_8when you turn socket bytes into text. Otherwise Java uses the platform default, and the client and server may disagree about characters like₹oré.
Sending and Receiving Many Messages
A socket connection stays open until one side closes it, so you can exchange many messages over the same connection. A simple protocol decides who speaks when; here, each request line gets exactly one reply line.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class Conversation {
public static void main(String[] args) throws Exception {
ServerSocket server = TextServer.start();
List<String> commands = List.of("UPPER java sockets", "SET city Chennai", "GET city", "GET country", "PING");
try (Socket socket = new Socket("localhost", 8093);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
// One request line, one response line, over the same connection
for (String command : commands) {
out.println(command);
System.out.printf("%-20s -> %s%n", command, in.readLine());
}
} finally {
server.close();
}
}
}
Output:
UPPER java sockets -> JAVA SOCKETS
SET city Chennai -> OK
GET city -> Chennai
GET country -> NOT_FOUND
PING -> ERROR unknown command: PING
How it works:
- All five commands travel over one TCP connection. Opening a new connection for every message would be much slower.
- Because the protocol is "one line in, one line out", the client always knows to call
readLine()once after eachprintln(). SETandGETshare server state, soGET cityreturns the value stored by the previous command.- The server answers unknown commands with an
ERRORline instead of closing the connection.
Note: TCP is a stream of bytes, not a stream of messages. One
println()on one side may arrive in several pieces on the other. Line-based reading withreadLine()puts the pieces back together; for binary data, use a length prefix withDataOutputStream.writeInt()before each message.
Detecting When the Server Closes the Connection
When the other side closes its connection, your next read reaches the end of stream. For a BufferedReader, readLine() returns null; for a raw InputStream, read() returns -1. This is how you know the conversation is over.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class EndOfStream {
public static void main(String[] args) throws Exception {
ServerSocket server = TextServer.start();
try (Socket socket = new Socket("localhost", 8093);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
out.println("QUIT");
// Keep reading until the server closes its side of the connection
String line;
int count = 0;
while ((line = in.readLine()) != null) {
System.out.println("Received: " + line);
count++;
}
System.out.println("readLine() returned null after " + count + " line(s): server closed the connection");
System.out.println("Our socket closed? " + socket.isClosed());
} finally {
server.close();
}
}
}
Output:
Received: BYE
readLine() returned null after 1 line(s): server closed the connection
Our socket closed? false
How it works:
- After
QUIT, the server sendsBYEand closes its socket. - The
while ((line = in.readLine()) != null)loop is the standard way to read until the end of stream. socket.isClosed()is stillfalse. It only reports whether your side was closed by callingclose(). It cannot tell you that the remote side went away; only a read returningnullor-1(or a write failing) does that.
Socket Timeouts: Connect and Read
By default, both connecting and reading can block forever. A server that is down, slow or unreachable could freeze your program. Java gives you two separate timeouts:
| Timeout | How to set it | Exception when it expires |
|---|---|---|
| Connect timeout | socket.connect(address, ms) | SocketTimeoutException ("Connect timed out") |
| Read timeout | socket.setSoTimeout(ms) | SocketTimeoutException ("Read timed out") |
If the target host is reachable but no program listens on the port, the OS rejects the connection at once with ConnectException: Connection refused.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
public class Timeouts {
public static void main(String[] args) throws Exception {
// 1. Nobody listens on port 8099: the connection is refused
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress("localhost", 8099), 2000); // 2 s connect timeout
} catch (ConnectException e) {
System.out.println("Connect failed: " + e.getMessage());
}
// 2. The server is slow: the read times out
ServerSocket server = TextServer.start();
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress("localhost", 8093), 2000);
socket.setSoTimeout(500); // wait at most 500 ms for each read
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
out.println("SLOW");
long start = System.nanoTime();
try {
System.out.println(in.readLine());
} catch (SocketTimeoutException e) {
long waited = (System.nanoTime() - start) / 1_000_000;
System.out.println("Read failed: " + e.getMessage() + " (after about " + (waited / 100 * 100) + " ms)");
}
} catch (IOException e) {
System.out.println("Unexpected: " + e);
} finally {
server.close();
}
}
}
Output:
Connect failed: Connection refused
Read failed: Read timed out (after about 500 ms)
How it works:
new Socket()creates an unconnected socket.connect(address, 2000)then connects with a 2-second limit. Use this form instead ofnew Socket(host, port)whenever the server might be unreachable.- Port 8099 has no listener, so the connection is refused immediately rather than timing out.
setSoTimeout(500)limits every blocking read to 500 ms. TheSLOWcommand takes 2 seconds, soreadLine()throwsSocketTimeoutException.- After a read timeout the socket is still open. You may retry the read, or close the socket and give up.
Java Socket Options
Socket options tune how the connection behaves. Most must be set before connect() to affect the connection setup.
| Option | Method | Effect |
|---|---|---|
TCP_NODELAY | setTcpNoDelay(true) | Send small writes immediately (turns off Nagle's algorithm); good for interactive protocols |
SO_KEEPALIVE | setKeepAlive(true) | The OS periodically checks idle connections and reports dead ones |
SO_TIMEOUT | setSoTimeout(ms) | Read timeout, as shown above |
SO_RCVBUF / SO_SNDBUF | setReceiveBufferSize(n) / setSendBufferSize(n) | Hints for OS buffer sizes |
SO_LINGER | setSoLinger(true, seconds) | How long close() waits to send unsent data |
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketOptions {
public static void main(String[] args) throws Exception {
ServerSocket server = TextServer.start();
try (Socket socket = new Socket()) {
// Options set before connect() apply to the new connection
socket.setTcpNoDelay(true); // send small writes immediately
socket.setKeepAlive(true); // let the OS probe idle connections
socket.setSoTimeout(3000); // read timeout in milliseconds
socket.connect(new InetSocketAddress("localhost", 8093), 2000);
System.out.println("TCP_NODELAY: " + socket.getTcpNoDelay());
System.out.println("SO_KEEPALIVE: " + socket.getKeepAlive());
System.out.println("SO_TIMEOUT: " + socket.getSoTimeout() + " ms");
System.out.println("Bound: " + socket.isBound());
socket.shutdownOutput(); // "I am done sending" (half-close)
System.out.println("Output shut down? " + socket.isOutputShutdown());
} finally {
server.close();
}
}
}
Output:
TCP_NODELAY: true
SO_KEEPALIVE: true
SO_TIMEOUT: 3000 ms
Bound: true
Output shut down? true
How it works:
- The options are applied to the unconnected socket and read back after
connect(). isBound()istruebecause the OS assigned a local address and port duringconnect().shutdownOutput()is a half-close: it sends end of stream to the server, but you can still read the server's remaining replies. This is useful when the server reads "until the client stops sending" before it answers.
Real-World Example: A Key-Value Store Client
Real applications hide socket details behind a small client class, the way a database driver does. This KeyValueClient opens one connection, sets timeouts, sends commands with a private call() method, turns protocol errors into exceptions and says QUIT before closing.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
// A reusable client for the line-based key-value protocol of TextServer
public class KeyValueClient implements AutoCloseable {
private final Socket socket;
private final PrintWriter out;
private final BufferedReader in;
public KeyValueClient(String host, int port) throws IOException {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 2000);
socket.setSoTimeout(3000);
out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
}
// Send one command and return the one-line reply
private String call(String command) throws IOException {
if (command.contains("\n")) throw new IllegalArgumentException("Commands must be one line");
out.println(command);
String reply = in.readLine();
if (reply == null) throw new IOException("Server closed the connection");
if (reply.startsWith("ERROR")) throw new IOException(reply);
return reply;
}
public void set(String key, String value) throws IOException {
if (key.contains(" ")) throw new IllegalArgumentException("Keys cannot contain spaces: " + key);
call("SET " + key + " " + value);
}
public Optional<String> get(String key) throws IOException {
String reply = call("GET " + key);
return reply.equals("NOT_FOUND") ? Optional.empty() : Optional.of(reply);
}
@Override
public void close() throws IOException {
try {
if (!socket.isClosed()) call("QUIT"); // polite goodbye
} catch (IOException ignored) {
// the server may already be gone
} finally {
socket.close();
}
}
public static void main(String[] args) throws Exception {
ServerSocket server = TextServer.start();
try {
// First connection stores some settings
try (KeyValueClient kv = new KeyValueClient("localhost", 8093)) {
kv.set("user:42:name", "Asha Rao");
kv.set("user:42:plan", "premium");
System.out.println("Saved two values");
}
// A second, separate connection reads them back
try (KeyValueClient kv = new KeyValueClient("localhost", 8093)) {
System.out.println("Name: " + kv.get("user:42:name").orElse("(none)"));
System.out.println("Plan: " + kv.get("user:42:plan").orElse("(none)"));
System.out.println("Email: " + kv.get("user:42:email").orElse("(none)"));
kv.set("bad key", "x");
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
} finally {
server.close();
}
// The server is stopped now, so connecting fails cleanly
try (KeyValueClient kv = new KeyValueClient("localhost", 8093)) {
kv.get("anything");
} catch (IOException e) {
System.out.println("Server down: " + e.getClass().getSimpleName() + " - " + e.getMessage());
}
}
}
Output:
Saved two values
Name: Asha Rao
Plan: premium
Email: (none)
Rejected: Keys cannot contain spaces: bad key
How it works:
- Safe connection setup. The constructor connects with a 2-second connect timeout and a 3-second read timeout, so a dead server can never freeze the caller.
- One place for the protocol.
call()sends a line and reads exactly one reply. It turns anullreply (closed connection) and anERRORreply intoIOExceptions, soset()andget()stay short. - Input checks before sending. A key with a space would break the
SET key valueformat, soset()rejects it withIllegalArgumentExceptionbefore anything is written to the socket. - Clear return types.
get()returnsOptional<String>, so "no value" (NOT_FOUND) is visible in the method's type instead of being a magic string. - Polite shutdown.
close()sendsQUITwhen the socket is still open, ignores errors from a server that is already gone, and always closes the socket infinally. - State lives on the server. The second connection reads values stored by the first, because the data is kept by the server, not by the socket.
- Failure is reported, not hidden. When the server is stopped, the constructor throws
ConnectException: Connection refused, which the caller catches and reports.
The same structure (connect with timeouts, one method per command, end-of-stream checks and a clean close()) applies to any TCP protocol you implement in Java. For connectionless UDP messaging, see Java DatagramSocket.