Networking Concepts in Java
Networking means two programs on different computers (or on the same computer) sending data to each other. Java has supported it from its first version through the package java.net, and newer code also uses java.net.http. Before writing any code, you need a handful of ideas: IP addresses, ports, protocols, and the roles of client and server. In this lesson, you will learn those ideas in plain words, see where each Java class fits, and run a first program in which a client and a server talk to each other.
The Key Terms
| Term | Meaning | Everyday comparison |
|---|---|---|
| IP address | A number that identifies a computer on a network, such as 192.168.1.20 (IPv4) or 2001:db8::1 (IPv6) | The street address of a building |
| Port | A number from 0 to 65535 that identifies one program on that computer | The flat number inside the building |
| Host name | A readable name such as www.poolstring.com | The name on the address label |
| DNS | The service that turns a host name into an IP address | A phone book |
| Protocol | An agreed set of rules for a conversation, such as TCP, UDP or HTTP | The language two people agree to speak |
| Socket | One end of a connection: an IP address plus a port | A telephone handset |
| Client | The program that starts the conversation | The caller |
| Server | The program that waits for clients and answers them | The person who picks up |
| localhost | The name for "this same computer", address 127.0.0.1 | Calling your own number |
Ports
| Range | Name | Used for |
|---|---|---|
| 0 to 1023 | Well-known ports | Standard services: 80 (HTTP), 443 (HTTPS), 22 (SSH), 25 (SMTP), 53 (DNS) |
| 1024 to 49151 | Registered ports | Applications: 3306 (MySQL), 5432 (PostgreSQL), 8080 (often a development web server) |
| 49152 to 65535 | Dynamic ports | Given out automatically by the operating system, for example to the client side of a connection |
Only one program can listen on a given port at a time. Asking for port 0 means "give me any free port", which the examples in this chapter use so they never clash with something already running.
TCP vs UDP
Two transport protocols carry almost all traffic:
| Point | TCP | UDP |
|---|---|---|
| Connection | A connection is set up first | No connection; each packet travels alone |
| Delivery | Guaranteed, or you get an error | Not guaranteed; packets can be lost |
| Order | Data arrives in the order it was sent | Packets can arrive out of order |
| Shape of the data | A continuous stream of bytes | Separate packets (datagrams) |
| Speed | Slower to start, more overhead | Faster, very little overhead |
| Used for | Web pages, email, file transfer, databases | Video calls, live streaming, games, DNS lookups |
| Java classes | Socket, ServerSocket | DatagramSocket, DatagramPacket |
Where the Java Classes Fit
| You want to... | Use | Lesson |
|---|---|---|
| Work with an IP address or look up a host name | InetAddress | "InetAddress Class in Java" |
| Open a TCP connection, or accept them | Socket, ServerSocket | "Socket Programming in Java" |
| Take a web address apart | URI, URL | "URL Class in Java" |
| Read a resource the old way | URLConnection, HttpURLConnection | The two lessons after that |
| Call a web API (the modern way) | HttpClient | "HttpClient in Java" |
| Send UDP packets | DatagramSocket, DatagramPacket | "DatagramSocket and DatagramPacket in Java" |
Example: A First Conversation
Let's see an example in which one program plays both roles: it starts a server on a free port, then connects to it as a client.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Hello {
public static void main(String[] args) throws Exception {
try (ServerSocket server = new ServerSocket(0)) {
int port = server.getLocalPort();
Thread serverThread = new Thread(() -> {
try (Socket client = server.accept();
PrintWriter out =
new PrintWriter(client.getOutputStream(), true)) {
out.println("Hello from the server");
} catch (Exception e) {
e.printStackTrace();
}
});
serverThread.start();
try (Socket socket = new Socket("localhost", port);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
System.out.println("Client received: " + in.readLine());
System.out.println("Port in valid range? "
+ (port >= 1024 && port <= 65535));
}
serverThread.join();
}
}
}Client received: Hello from the server
Port in valid range? trueExplanation:
new ServerSocket(0)opens a listening socket on any free port;getLocalPort()tells us which one we got.- The server thread calls
accept(), which waits until a client connects and then returns aSocketfor talking to that client. new Socket("localhost", port)is the client connecting. The namelocalhostis resolved to127.0.0.1, and the port selects our server.- Each side has an input stream and an output stream. What the server writes with
println, the client reads withreadLine. - try-with-resources closes every socket, which also ends the connection.
Real programs put the server and the client in two separate programs, usually on two machines. Keeping both in one file lets you run it with a single command.
Common Mistakes
Confusing the IP address with the port. The address chooses the machine; the port chooses the program on it.
Expecting UDP to be reliable. If you need every byte, in order, use TCP.
Hard-coding a port that is already in use. The program fails with BindException. Make the port configurable.
Forgetting that network calls block. accept() and read() wait until something happens; don't call them on a thread that must stay responsive.
Interview Corner
What is the difference between TCP and UDP?
TCP is connection-oriented: a connection is established first, delivery is guaranteed and ordered, and data is a continuous byte stream. It has more overhead and is used for the web, email, file transfer and databases. UDP is connectionless: each datagram is sent independently, with no guarantee of delivery or order, and very little overhead. It suits video and voice calls, games and DNS. In Java, TCP uses Socket and ServerSocket; UDP uses DatagramSocket and DatagramPacket.
What is a socket?
A socket is one endpoint of a two-way communication link between two programs, identified by an IP address and a port number. A TCP connection is identified by the pair of sockets at its two ends. In Java, a client creates a Socket; a server creates a ServerSocket and gets a Socket for each client from accept().
Practice
- Easy: Change
Helloso the server sends two lines and the client prints both. - Harder: Make the client send its name first, and have the server reply "Hello, " plus that name.
Key Takeaways
Was this tutorial helpful?