Networking Basics (Sockets) in Java
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.
Socket
Represents the client side of a two-way network connection to a specific server address and port.
ServerSocket
Listens on a specific port for incoming connection attempts from clients.
accept()
Blocks until a client actually connects, then returns a new Socket representing that specific connection.
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.
The foundation beneath higher-level networking
HTTP clients and web servers are themselves built on top of this same lower-level socket API.
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(); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.