Learn Java
import com.learnjava.advancedjava.NetworkingSockets;

Networking Basics (Sockets) in Java

@Concept

A socket represents one endpoint of a two-way network connection between two programs, and Java's java.net package provides Socket for the client side of a connection and ServerSocket for the server side that listens for and accepts incoming ones. A server creates a ServerSocket bound to a specific port and calls accept(), which blocks until a client actually connects, at which point it returns a Socket representing that specific new connection; a client creates a Socket directly, giving it the server's address and port, which attempts to establish that connection immediately.

Once connected, both sides read and write through ordinary input and output streams obtained from the socket — exactly the same kind of streams used for file I/O elsewhere — exchanging raw bytes, or text wrapped in a reader or writer, back and forth. This low-level socket API is what higher-level things like HTTP clients and web servers are themselves ultimately built on top of, even though most everyday application code reaches for a higher-level HTTP library rather than working with raw sockets directly.

@HowItWorks
1

Socket

Represents the client side of a two-way network connection to a specific server address and port.

2

ServerSocket

Listens on a specific port for incoming connection attempts from clients.

3

accept()

Blocks until a client actually connects, then returns a new Socket representing that specific connection.

4

Reading and writing

Both sides exchange data through ordinary input and output streams obtained from their socket, the same kind used for file I/O.

5

The foundation beneath higher-level networking

HTTP clients and web servers are themselves built on top of this same lower-level socket API.

@Example
import java.io.*;
import java.net.*;
 
public class SocketDemo {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(0);
int port = server.getLocalPort();
 
Thread serverThread = new Thread(() -> {
try (Socket conn = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
PrintWriter out = new PrintWriter(conn.getOutputStream(), true)) {
String received = in.readLine();
out.println("Echo: " + received);
} catch (IOException e) {
// ignored for this example
}
});
serverThread.start();
 
try (Socket client = new Socket("localhost", port);
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
out.println("Hello, server");
System.out.println(in.readLine());
}
 
serverThread.join();
}
}
Output
Echo: Hello, server
1ServerSocket(0) binds to an available port chosen by the operating system, and the server thread's accept() call then blocks until a client actually connects.
2The main thread, acting as the client, connects a new Socket to that same port on localhost and sends one line of text.
3The server thread reads that line and writes back a response prefixed with "Echo: ", exchanged over the same connection.
4The client reads that response, and the single println call prints it, confirming the round trip over an actual, if local, network connection.
@UseCases
Building a simple client-server application that exchanges messages over a network
Understanding the low-level mechanism that HTTP clients and web servers are themselves built on top of
Recognizing when a higher-level library, rather than raw sockets, is the more practical choice for everyday networking
Debugging a connection-refused error caused by a client connecting to a port nothing is actually listening on

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.