BackendBench
Coffee

Unravel โ€บ Java concepts โ€บ I/O and files

I/O and data

Sockets, URLs and networking

A Socket is one end of a TCP connection: you write bytes in and read bytes out.

Learn these first

At a glance

Mental model

A phone call.

What happens, in order
  1. 1new Socket("example.com", 80) connects; socket.getInputStream() and getOutputStream() give the two directionsTCP delivers a stream of bytes, not messages: you need your own framing (line breaks, length prefix).
  2. 2ServerSocket server = new ServerSocket(8080); Socket client = server.accept(); blocks until someone connects, normally handing each client to a thread or executor
  3. 3URI.create("https://a.com/x?y=1") parses; getHost(), getPath(), getQuery() read the partsPrefer URI over URL (whose equals can do DNS lookups).
  4. 4URLEncoder.encode(text, UTF_8) makes text safe in a query stringMost real code uses an HTTP client or a framework rather than raw sockets.
Remember
Watch out
No timeoutsAssuming one write equals one read on the other sideForgetting to close the socket in a finally blockBuilding query strings without encoding
Example (highlighted lines explain it)
import java.io.*;import java.net.*;public class Echo {  static void serve(int port) throws IOException {    try (ServerSocket server = new ServerSocket(port)) {      while (true) {        try (Socket client = server.accept();             BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));             PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {          client.setSoTimeout(5000);          String line = in.readLine();          out.println("echo " + line);        }      }    }  }  static String host(String s) { return URI.create(s).getHost(); }}
  1. line 5 uses ServerSocket, the core of Sockets, URLs and networking
  2. line 7 uses Socket, the core of Sockets, URLs and networking
  3. line 17 uses URI, the core of Sockets, URLs and networking
Read the full explanation (about 1 min)

A Socket is one end of a TCP connection: you write bytes in and read bytes out. ServerSocket waits for incoming connections; URI and URL parse and build addresses.

A mental model

A phone call. The server sits by the phone (ServerSocket.accept), the client dials (new Socket(host, port)), and once connected both sides can talk and listen until one hangs up.

How it works

new Socket("example.com", 80) connects; socket.getInputStream() and getOutputStream() give the two directions. TCP delivers a stream of bytes, not messages: you need your own framing (line breaks, length prefix).

ServerSocket server = new ServerSocket(8080); Socket client = server.accept(); blocks until someone connects, normally handing each client to a thread or executor.

URI.create("https://a.com/x?y=1") parses; getHost(), getPath(), getQuery() read the parts. Prefer URI over URL (whose equals can do DNS lookups).

URLEncoder.encode(text, UTF_8) makes text safe in a query string. Most real code uses an HTTP client or a framework rather than raw sockets.

Going deeper

Always set timeouts: socket.connect(addr, 3000) and setSoTimeout(5000). Without them a dead peer makes the thread hang forever.

Reading until -1 or null means the peer closed the connection; a half-sent message ends with an IOException (connection reset). Treat network calls as failing often.

One thread per connection does not scale to tens of thousands of clients; use NIO selectors (SocketChannel, Netty), or virtual threads.

Under the hood

A Socket wraps an operating-system file descriptor; reads and writes are system calls on the kernel's TCP buffers. DNS names are resolved by InetAddress.getByName, which caches results (networkaddress.cache.ttl).

Common mistakes

  • No timeouts.
  • Assuming one write equals one read on the other side.
  • Forgetting to close the socket in a finally block.
  • Building query strings without encoding.

How Unravel recognises it

When you paste code, Unravel looks for these signs of sockets, urls and networking. Spotting them yourself is a good habit when you read unfamiliar code:

Part of a learning path

Related concepts

Builds on this

Frequently asked questions

What is Sockets, URLs and networking?

A Socket is one end of a TCP connection: you write bytes in and read bytes out. ServerSocket waits for incoming connections; URI and URL parse and build addresses.

What are the most common mistakes with Sockets, URLs and networking?

No timeouts. Assuming one write equals one read on the other side. Forgetting to close the socket in a finally block. Building query strings without encoding.

How can I see Sockets, URLs and networking in real code?

Paste your own Java into Unravel and it will point out where sockets, urls and networking appears, explain how it works at the detail level you choose, and draw the flow of the code around it.