Networking Concepts in Java

Naveen AnamaneniUpdated · 7 min read

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

TermMeaningEveryday comparison
IP addressA 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
PortA number from 0 to 65535 that identifies one program on that computerThe flat number inside the building
Host nameA readable name such as www.poolstring.comThe name on the address label
DNSThe service that turns a host name into an IP addressA phone book
ProtocolAn agreed set of rules for a conversation, such as TCP, UDP or HTTPThe language two people agree to speak
SocketOne end of a connection: an IP address plus a portA telephone handset
ClientThe program that starts the conversationThe caller
ServerThe program that waits for clients and answers themThe person who picks up
localhostThe name for "this same computer", address 127.0.0.1Calling your own number

Ports

RangeNameUsed for
0 to 1023Well-known portsStandard services: 80 (HTTP), 443 (HTTPS), 22 (SSH), 25 (SMTP), 53 (DNS)
1024 to 49151Registered portsApplications: 3306 (MySQL), 5432 (PostgreSQL), 8080 (often a development web server)
49152 to 65535Dynamic portsGiven 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:

PointTCPUDP
ConnectionA connection is set up firstNo connection; each packet travels alone
DeliveryGuaranteed, or you get an errorNot guaranteed; packets can be lost
OrderData arrives in the order it was sentPackets can arrive out of order
Shape of the dataA continuous stream of bytesSeparate packets (datagrams)
SpeedSlower to start, more overheadFaster, very little overhead
Used forWeb pages, email, file transfer, databasesVideo calls, live streaming, games, DNS lookups
Java classesSocket, ServerSocketDatagramSocket, DatagramPacket
TCP sets up a reliable stream; UDP just sends packets

Where the Java Classes Fit

You want to...UseLesson
Work with an IP address or look up a host nameInetAddress"InetAddress Class in Java"
Open a TCP connection, or accept themSocket, ServerSocket"Socket Programming in Java"
Take a web address apartURI, URL"URL Class in Java"
Read a resource the old wayURLConnection, HttpURLConnectionThe two lessons after that
Call a web API (the modern way)HttpClient"HttpClient in Java"
Send UDP packetsDatagramSocket, 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.

Hello.java▶ Try it
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();
        }
    }
}
Output
Client received: Hello from the server
Port in valid range? true

Explanation:

  1. new ServerSocket(0) opens a listening socket on any free port; getLocalPort() tells us which one we got.
  2. The server thread calls accept(), which waits until a client connects and then returns a Socket for talking to that client.
  3. new Socket("localhost", port) is the client connecting. The name localhost is resolved to 127.0.0.1, and the port selects our server.
  4. Each side has an input stream and an output stream. What the server writes with println, the client reads with readLine.
  5. 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

  1. Easy: Change Hello so the server sends two lines and the client prints both.
  2. Harder: Make the client send its name first, and have the server reply "Hello, " plus that name.

Quick check: Networking concepts

4 questions
1What does a port number identify?
2Which protocol guarantees ordered delivery?
3What does the name localhost refer to?
4What does DNS do?

Key Takeaways

Was this tutorial helpful?

Lesson 475 of 482