Networking basics (overview)
◈ 4 cardsSocket/ServerSocket, the client–server shape, and getting streams over a connection.
Sockets: streams over the network
Java networking reuses everything you learned about streams. A TCP connection is just two streams — one to read, one to write — that happen to run between two machines. The two endpoints play different roles:
- A
ServerSocketlistens on a port and accepts incoming connections.accept()blocks until a client connects, then returns aSocketrepresenting that one conversation. - A
Socketis one end of a live connection. The client creates one by naming the server's host and port; the server gets one back fromaccept(). Either side then callsgetInputStream()/getOutputStream()and reads/writes exactly like any other stream.
The minimal echo server
try (ServerSocket server = new ServerSocket(8080);
Socket conn = server.accept()) { // blocks for a client
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
PrintWriter out = new PrintWriter(conn.getOutputStream(), true);
String line = in.readLine();
out.println("echo: " + line); // send it back
}
The true second argument to PrintWriter turns on auto-flush so each println is pushed to the network immediately instead of sitting in the buffer — important for an interactive protocol where the other side is waiting for your reply.
The matching client
try (Socket s = new Socket("localhost", 8080)) {
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
out.println("hello");
System.out.println(in.readLine()); // prints: echo: hello
}
Notice the symmetry: the server's output stream feeds the client's input stream and vice versa. To serve many clients at once, the server loops on accept() and hands each returned Socket to its own thread — which connects directly to the concurrency you study in Module 10.
URL for higher-level access
For fetching a web resource you rarely touch raw sockets; java.net.URL wraps the protocol. new URL("http://example.com").openStream() hands back an InputStream of the response body, which you wrap in a BufferedReader like any other text source — the same stream model, one layer up.