ZetCode

Java Socket

last modified November 19, 2026 Java 25

In this article we do network programming in Java with sockets. We create TCP clients for the daytime, whois, and HTTP protocols, write our own TCP servers, handle several clients with virtual threads, and send datagrams over UDP.

Socket programming is low-level. Its purpose here is to show what happens under the hood of network protocols. For real HTTP work, a higher-level API such as the Java HttpClient is a better choice.

Socket

In programming, a socket is an endpoint of a communication between two programs running on a network. A program reads from and writes to a socket much like it does with a file. The Socket class represents a client socket and the ServerSocket class a server socket.

Note: In networking, the term socket has also a narrower meaning: the combination of an IP address and a port number.

A port is a number from 0 to 65535 that identifies a service on a host. A ServerSocket is bound to a port and clients connect to that port. Well-known services have standard ports; for instance, HTTP uses port 80 and whois port 43.

Socket and ServerSocket work with the TCP protocol. TCP is connection-oriented; it delivers a reliable, ordered stream of bytes. It is used by services such as HTTP, SMTP, or SSH. The DatagramSocket and DatagramPacket classes work with the UDP protocol. UDP sends independent packets with no guarantee of delivery or order; in exchange, it has less overhead. It is used by services such as DNS or VoIP.

The examples use compact source files and instance main methods, which are final in Java 25. A compact source file imports all packages of the java.base module automatically, so classes such as Socket, BufferedReader, or StandardCharsets need no import statements. We run each example with the java launcher, for instance java TimeClient.java.

Daytime client

The daytime protocol, defined in RFC 867, is one of the simplest network services. The client connects to port 13 and the server sends back the current date and time and closes the connection. The client sends no data.

TimeClient.java
void main() throws IOException {

    var hostname = "time.nist.gov";
    int port = 13;

    try (var socket = new Socket(hostname, port)) {

        InputStream in = socket.getInputStream();
        byte[] data = in.readAllBytes();

        IO.println(new String(data, StandardCharsets.US_ASCII).strip());
    }
}

The program connects to the daytime service of the National Institute of Standards and Technology (NIST) and prints the response.

try (var socket = new Socket(hostname, port)) {

The constructor resolves the host name, creates a stream socket, and connects it to the given port. The try-with-resources statement closes the socket when the block ends.

InputStream in = socket.getInputStream();
byte[] data = in.readAllBytes();

The getInputStream method returns the stream of bytes coming from the server. The readAllBytes method reads until the end of the stream, which happens when the server closes the connection.

IO.println(new String(data, StandardCharsets.US_ASCII).strip());

Sockets transfer bytes, not text. We decode the bytes into a string with an explicit charset; the daytime response is plain ASCII. The strip method removes the newline characters that surround the response.

The NIST format contains the Modified Julian Date, the date in YY-MM-DD form, the UTC time, and several status fields. NIST servers refuse clients that query more often than once in four seconds; in such a case the response is empty.

$ java TimeClient.java
61363 26-11-19 14:03:28 00 0 0   3.0 UTC(NIST) *

Whois client

In the daytime protocol, the client only reads. Most protocols require the client to send a request first. Whois, defined in RFC 3912, is a simple query/response protocol on port 43. It is used to find information about the holders of domain names and IP address blocks. The client sends a query terminated with CRLF, and the server replies and closes the connection.

WhoisClient.java
void main() throws IOException {

    var server = "whois.iana.org";
    int port = 43;
    var query = "example.com";

    try (var socket = new Socket(server, port);
         var writer = new PrintWriter(new OutputStreamWriter(
                 socket.getOutputStream(), StandardCharsets.UTF_8));
         var reader = new BufferedReader(new InputStreamReader(
                 socket.getInputStream(), StandardCharsets.UTF_8))) {

        writer.print(query + "\r\n");
        writer.flush();

        String line;

        while ((line = reader.readLine()) != null) {
            IO.println(line);
        }
    }
}

The program asks the IANA whois server about the example.com domain.

var writer = new PrintWriter(new OutputStreamWriter(
        socket.getOutputStream(), StandardCharsets.UTF_8));

The getOutputStream method returns the stream of bytes going to the server. The OutputStreamWriter encodes characters into bytes with the given charset, and the PrintWriter adds convenient print methods.

var reader = new BufferedReader(new InputStreamReader(
        socket.getInputStream(), StandardCharsets.UTF_8))

In the other direction, the InputStreamReader decodes the bytes into characters and the BufferedReader lets us read the response line by line.

writer.print(query + "\r\n");
writer.flush();

We send the query terminated with the CRLF sequence. We do not use println, because it writes the line separator of the platform, which is only LF on Linux and macOS. The writer is buffered; without flush, the query would stay in the buffer and both sides would wait for each other forever.

The IANA server knows the top-level domains. For a full record of a .com domain, we would query the server given in its refer field, such as whois.verisign-grs.com. Domain registrars often hide the details about owners.

$ java WhoisClient.java
% IANA WHOIS server
% for more information on IANA, visit http://www.iana.org
% This query returned 1 object

domain:       EXAMPLE.COM

organisation: Internet Assigned Numbers Authority

created:      1992-01-01
source:       IANA

GET request

HTTP is also a text protocol on top of TCP, so we can speak it through a socket. The HTTP GET request retrieves a resource. The request consists of a request line, header lines, and an empty line; each line ends with CRLF.

GetRequest.java
void main() throws IOException {

    var hostname = "example.com";
    int port = 80;

    try (var socket = new Socket(hostname, port);
         var writer = new PrintWriter(new OutputStreamWriter(
                 socket.getOutputStream(), StandardCharsets.US_ASCII));
         var reader = new BufferedReader(new InputStreamReader(
                 socket.getInputStream(), StandardCharsets.UTF_8))) {

        writer.print("GET / HTTP/1.1\r\n");
        writer.print("Host: " + hostname + "\r\n");
        writer.print("Connection: close\r\n");
        writer.print("\r\n");
        writer.flush();

        String line;

        while ((line = reader.readLine()) != null) {
            IO.println(line);
        }
    }
}

The program retrieves the home page of example.com over plain HTTP on port 80.

writer.print("GET / HTTP/1.1\r\n");
writer.print("Host: " + hostname + "\r\n");
writer.print("Connection: close\r\n");
writer.print("\r\n");
writer.flush();

The request line asks for the / path using HTTP/1.1. The Host header is mandatory in HTTP/1.1, since one server may host many websites. HTTP/1.1 connections are persistent by default; the Connection: close header asks the server to close the connection after the response, so that our reading loop ends. The empty line finishes the request. The message syntax is described in RFC 9112.

The response starts with a status line and headers, followed by an empty line and the body. The server sends the body with chunked transfer encoding: the 241 line is the size of the following chunk in hexadecimal and the 0 line marks the last chunk. A real HTTP client decodes these chunks for us.

$ java GetRequest.java
HTTP/1.1 200 OK
Date: Thu, 19 Nov 2026 14:01:35 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Server: cloudflare
Last-Modified: Wed, 18 Nov 2026 17:47:37 GMT
Allow: GET, HEAD
Accept-Ranges: bytes
Age: 14095
cf-cache-status: HIT
CF-RAY: a5cfbf6ebdde5b90-VIE
alt-svc: h3=":443"; ma=86400

241
<!doctype html><html lang=en><head><meta charset=utf-8>...</html>

0

HEAD request

The HEAD method is identical to GET, except that the server returns only the status line and the headers, without a body. In this example, we also parse the response instead of printing it as is.

HeadRequest.java
void main() throws IOException {

    var hostname = "example.com";
    int port = 80;

    try (var socket = new Socket(hostname, port);
         var writer = new PrintWriter(new OutputStreamWriter(
                 socket.getOutputStream(), StandardCharsets.US_ASCII));
         var reader = new BufferedReader(new InputStreamReader(
                 socket.getInputStream(), StandardCharsets.US_ASCII))) {

        writer.print("HEAD / HTTP/1.1\r\n");
        writer.print("Host: " + hostname + "\r\n");
        writer.print("User-Agent: Java socket client\r\n");
        writer.print("Connection: close\r\n");
        writer.print("\r\n");
        writer.flush();

        String statusLine = reader.readLine();
        IO.println("Status: " + statusLine);

        String line;

        while ((line = reader.readLine()) != null && !line.isEmpty()) {

            int idx = line.indexOf(':');
            var name = line.substring(0, idx);
            var value = line.substring(idx + 1).strip();

            System.out.printf("%-16s %s%n", name, value);
        }
    }
}

The program sends a HEAD request and prints the status line and a table of the response headers.

writer.print("HEAD / HTTP/1.1\r\n");
writer.print("Host: " + hostname + "\r\n");
writer.print("User-Agent: Java socket client\r\n");

We issue a HEAD request. The optional User-Agent header identifies our client to the server.

String statusLine = reader.readLine();
IO.println("Status: " + statusLine);

The first line of the response is the status line. It contains the protocol version, the status code, and the reason phrase.

while ((line = reader.readLine()) != null && !line.isEmpty()) {

    int idx = line.indexOf(':');
    var name = line.substring(0, idx);
    var value = line.substring(idx + 1).strip();

    System.out.printf("%-16s %s%n", name, value);
}

Each header is a name and a value separated by a colon. The headers end with an empty line, so the loop stops there. This lets us read the headers of a GET response as well, without reading its body.

$ java HeadRequest.java
Status: HTTP/1.1 200 OK
Date             Thu, 19 Nov 2026 14:01:37 GMT
Content-Type     text/html; charset=utf-8
Connection       close
Server           cloudflare
Last-Modified    Wed, 18 Nov 2026 17:47:37 GMT
Allow            GET, HEAD
Accept-Ranges    bytes
Age              14097
cf-cache-status  HIT
CF-RAY           a5cfbf774c1a5b5d-VIE
alt-svc          h3=":443"; ma=86400

Socket timeouts

By default, socket operations can block for a long time. Connecting to an unreachable host may take minutes, and a read from a silent server waits forever. In real programs, we set timeouts and handle network errors.

SocketTimeouts.java
String daytime(String hostname) throws IOException {

    try (var socket = new Socket()) {

        socket.connect(new InetSocketAddress(hostname, 13), 3000);
        socket.setSoTimeout(5000);

        byte[] data = socket.getInputStream().readAllBytes();
        return new String(data, StandardCharsets.US_ASCII).strip();
    }
}

void main() {

    String[] hosts = { "time.nist.gov", "10.255.255.1", "localhost" };

    for (var host : hosts) {

        try {
            IO.println(host + ": " + daytime(host));
        } catch (SocketTimeoutException e) {
            IO.println(host + ": timeout - " + e.getMessage());
        } catch (IOException e) {
            IO.println(host + ": error - " + e.getMessage());
        }
    }
}

The program queries the daytime service on three hosts. The first one works, the second one does not respond, and the third one has no daytime service.

try (var socket = new Socket()) {

    socket.connect(new InetSocketAddress(hostname, 13), 3000);

The no-argument constructor creates an unconnected socket. The connect method then connects it to an InetSocketAddress, which pairs a host and a port. The second argument is the connect timeout in milliseconds.

socket.setSoTimeout(5000);

The setSoTimeout method sets the read timeout. If no data arrives within five seconds, a read throws SocketTimeoutException. The socket stays open, so we could retry the read.

} catch (SocketTimeoutException e) {
    IO.println(host + ": timeout - " + e.getMessage());
} catch (IOException e) {
    IO.println(host + ": error - " + e.getMessage());
}

SocketTimeoutException is a subclass of IOException, so it must be caught first. Other failures, such as an unknown host or a refused connection, are reported as other IOException subclasses. The 10.255.255.1 address belongs to a private range and nothing answers there, so the connection times out after three seconds. On localhost, no program listens on port 13 and the operating system refuses the connection at once.

$ java SocketTimeouts.java
time.nist.gov: 61363 26-11-19 14:03:19 00 0 0 594.4 UTC(NIST) *
10.255.255.1: timeout - Connect timed out
localhost: error - Connection refused

Date server

So far we have written clients. A server creates a ServerSocket bound to a port and waits for clients. Our first server sends the current date to each client that connects, similar to the daytime service.

DateServer.java
void main() throws IOException {

    int port = 8081;

    try (var server = new ServerSocket(port)) {

        IO.println("Date server listening on port " + port);

        while (true) {

            try (var socket = server.accept();
                 var writer = new PrintWriter(socket.getOutputStream(), true)) {

                IO.println("Connection from " + socket.getRemoteSocketAddress());
                writer.println(LocalDate.now());
            }
        }
    }
}

The server runs until we terminate it with Ctrl+C. Ports below 1024 usually require administrator privileges, so we use port 8081.

try (var server = new ServerSocket(port)) {

The ServerSocket is bound to port 8081 on all network interfaces of the machine. If another program already uses the port, the constructor throws a BindException.

try (var socket = server.accept();
     var writer = new PrintWriter(socket.getOutputStream(), true)) {

The accept method blocks until a client connects. It returns a new Socket for the communication with this client; the server socket keeps listening for others. The second argument of the PrintWriter enables automatic flushing after each println.

IO.println("Connection from " + socket.getRemoteSocketAddress());
writer.println(LocalDate.now());

We log the address and port of the client and send it the current date. Closing the socket at the end of the try block ends the connection, which tells the client that the response is complete.

$ java DateServer.java
Date server listening on port 8081
Connection from /127.0.0.1:40000
Connection from /127.0.0.1:40004

Date client

The client for our date server connects to localhost, the local machine, and reads one line.

DateClient.java
void main() throws IOException {

    try (var socket = new Socket("localhost", 8081);
         var reader = new BufferedReader(new InputStreamReader(
                 socket.getInputStream()))) {

        IO.println("Today is " + reader.readLine());
    }
}

We start the server in one terminal and run the client in another. The date is plain ASCII text, so the default charset works for it. The two connections in the server output above come from these two runs.

$ java DateClient.java
Today is 2026-11-19
$ java DateClient.java
Today is 2026-11-19

Reverse server

The date server sends one line and closes the connection. Now the client and the server exchange several messages over one connection. The server reverses each line it receives and sends it back. When the client sends bye, the server answers bye and closes the connection.

ReverseServer.java
void main() throws IOException {

    int port = 8081;

    try (var server = new ServerSocket(port)) {

        IO.println("Reverse server listening on port " + port);

        while (true) {

            try (var socket = server.accept();
                 var reader = new BufferedReader(new InputStreamReader(
                         socket.getInputStream(), StandardCharsets.UTF_8));
                 var writer = new PrintWriter(new OutputStreamWriter(
                         socket.getOutputStream(), StandardCharsets.UTF_8), true)) {

                IO.println("Client connected");

                String line;

                while ((line = reader.readLine()) != null &&
                        !line.equals("bye")) {

                    IO.println("Received: " + line);
                    writer.println(new StringBuilder(line).reverse());
                }

                writer.println("bye");
                IO.println("Client disconnected");
            }
        }
    }
}

The server serves one client at a time. Other clients that connect in the meantime wait in the backlog queue of the server socket until the current client says bye.

while ((line = reader.readLine()) != null &&
        !line.equals("bye")) {

    IO.println("Received: " + line);
    writer.println(new StringBuilder(line).reverse());
}

The inner loop reads lines until the client sends bye. The readLine method returns null when the client closes the connection without saying goodbye, for instance when it is killed; the server then moves on to the next client instead of looping forever.

writer.println("bye");

We confirm the end of the conversation, so the client does not wait for a response that never comes.

$ java ReverseServer.java
Reverse server listening on port 8081
Client connected
Received: hello there
Received: an old falcon
Client disconnected

Reverse client

The client reads text from the console, sends it to the server, and prints the reply.

ReverseClient.java
void main() throws IOException {

    try (var socket = new Socket("localhost", 8081);
         var reader = new BufferedReader(new InputStreamReader(
                 socket.getInputStream(), StandardCharsets.UTF_8));
         var writer = new PrintWriter(new OutputStreamWriter(
                 socket.getOutputStream(), StandardCharsets.UTF_8), true)) {

        String text;

        do {
            text = IO.readln("Enter text: ");

            if (text == null) {
                text = "bye";
            }

            writer.println(text);
            IO.println("Server: " + reader.readLine());

        } while (!text.equals("bye"));
    }
}

Both programs use UTF-8 explicitly, so text in any language survives the trip regardless of the default charsets of the two machines.

text = IO.readln("Enter text: ");

if (text == null) {
    text = "bye";
}

The IO.readln method prints a prompt and reads a line from the console. It returns null at the end of input, for example when we press Ctrl+D; we then end the session properly.

writer.println(text);
IO.println("Server: " + reader.readLine());

We send the line and wait for the response. The client and the server follow the same simple protocol: one line request, one line response.

$ java ReverseClient.java
Enter text: hello there
Server: ereht olleh
Enter text: an old falcon
Server: noclaf dlo na
Enter text: bye
Server: bye

Concurrent server

To serve several clients at the same time, the server hands each accepted connection to a separate thread. Virtual threads, final since Java 21, are cheap enough to create one per connection, even for thousands of clients.

ConcurrentReverseServer.java
void handle(Socket socket) {

    var client = socket.getRemoteSocketAddress();

    try (socket;
         var reader = new BufferedReader(new InputStreamReader(
                 socket.getInputStream(), StandardCharsets.UTF_8));
         var writer = new PrintWriter(new OutputStreamWriter(
                 socket.getOutputStream(), StandardCharsets.UTF_8), true)) {

        IO.println(client + " connected");

        String line;

        while ((line = reader.readLine()) != null &&
                !line.equals("bye")) {

            IO.println(client + ": " + line);
            writer.println(new StringBuilder(line).reverse());
        }

        writer.println("bye");

    } catch (IOException e) {
        IO.println(client + " error: " + e.getMessage());
    }

    IO.println(client + " disconnected");
}

void main() throws IOException {

    int port = 8081;

    try (var server = new ServerSocket(port)) {

        IO.println("Reverse server listening on port " + port);

        while (true) {
            Socket socket = server.accept();
            Thread.ofVirtual().start(() -> handle(socket));
        }
    }
}

The conversation with a client moves into the handle method. The main loop only accepts connections. It works with the ReverseClient from the previous section.

Socket socket = server.accept();
Thread.ofVirtual().start(() -> handle(socket));

The Thread.ofVirtual method returns a builder for virtual threads; start runs the lambda in a new thread. The main thread immediately returns to accept and waits for the next client.

try (socket;
     var reader = ...

The socket is created outside of handle, but the method is responsible for closing it. A try-with-resources statement can manage an existing effectively final variable, so we list socket as the first resource.

} catch (IOException e) {
    IO.println(client + " error: " + e.getMessage());
}

A lambda passed to a thread cannot throw checked exceptions, and an error in one connection must not stop the server. Therefore, handle catches the exceptions itself.

We run two clients in two terminals. The output shows that the second client connects and is served while the first one is still connected; the messages of both clients are interleaved.

$ java ConcurrentReverseServer.java
Reverse server listening on port 8081
/127.0.0.1:60734 connected
/127.0.0.1:60734: first client
/127.0.0.1:60746 connected
/127.0.0.1:60734: falcon
/127.0.0.1:60734 disconnected
/127.0.0.1:60746: second client
/127.0.0.1:60746 disconnected

UDP quote client

UDP has no connections and no streams. A program puts data into a DatagramPacket, addresses it, and sends it with a DatagramSocket. Each packet travels on its own and may be lost, duplicated, or arrive out of order. The Quote of the Day (QOTD) service, defined in RFC 865, replies to any datagram sent to port 17 with a short quote.

QuoteClient.java
void main() throws IOException {

    var address = InetAddress.getByName("djxmmx.net");
    int port = 17;

    try (var socket = new DatagramSocket()) {

        socket.setSoTimeout(5000);

        var request = new DatagramPacket(new byte[1], 1, address, port);
        socket.send(request);

        var buffer = new byte[512];
        var response = new DatagramPacket(buffer, buffer.length);
        socket.receive(response);

        var quote = new String(buffer, 0, response.getLength(),
                StandardCharsets.US_ASCII);
        IO.println(quote.strip());
    }
}

The program sends a datagram to a public QOTD server and prints the quote it receives. Public QOTD servers are rare; if this one stops working, the next section shows how to run our own UDP server.

var address = InetAddress.getByName("djxmmx.net");

The InetAddress.getByName method resolves a host name to an IP address.

try (var socket = new DatagramSocket()) {

    socket.setSoTimeout(5000);

A DatagramSocket created without arguments is bound to a free port chosen by the system. Since a UDP packet may get lost, we always set a receive timeout; otherwise, receive could block forever.

var request = new DatagramPacket(new byte[1], 1, address, port);
socket.send(request);

The service ignores the content of the request, so we send a packet with a single byte. An outgoing packet carries its data, the destination address, and the port.

var buffer = new byte[512];
var response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);

An incoming packet needs a buffer. RFC 865 limits the quote to 512 characters. The receive method blocks until a packet arrives and fills the buffer; getLength then returns the number of bytes received.

$ java QuoteClient.java
"My spelling is Wobbly.  It's good spelling but it Wobbles, and the letters
 get in the wrong places." A. A. Milne (1882-1958)

UDP server

A UDP server binds a DatagramSocket to a known port. There is no accept; the same socket receives packets from all clients, and each packet tells where it came from. Our server converts the received text to uppercase and sends it back.

UdpUpperServer.java
void main() throws IOException {

    int port = 8082;

    try (var socket = new DatagramSocket(port)) {

        IO.println("UDP server listening on port " + port);
        var buffer = new byte[1024];

        while (true) {

            var packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);

            var text = new String(packet.getData(), 0, packet.getLength(),
                    StandardCharsets.UTF_8);
            IO.println(packet.getSocketAddress() + ": " + text);

            byte[] reply = text.toUpperCase().getBytes(StandardCharsets.UTF_8);
            socket.send(new DatagramPacket(reply, reply.length,
                    packet.getSocketAddress()));
        }
    }
}

The server answers each packet with a packet of its own.

socket.send(new DatagramPacket(reply, reply.length,
        packet.getSocketAddress()));

The getSocketAddress method of the received packet returns the address and port of the sender. We use it as the destination of the reply.

UDP client

The client sends three words to the server and prints the replies.

UdpUpperClient.java
void main() throws IOException {

    var server = new InetSocketAddress("localhost", 8082);
    String[] words = { "falcon", "sky", "čerešňa" };

    try (var socket = new DatagramSocket()) {

        socket.setSoTimeout(2000);
        var buffer = new byte[1024];

        for (var word : words) {

            byte[] data = word.getBytes(StandardCharsets.UTF_8);
            socket.send(new DatagramPacket(data, data.length, server));

            var response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);

            IO.println(word + " -> " + new String(buffer, 0,
                    response.getLength(), StandardCharsets.UTF_8));
        }
    }
}

The client sends each word in its own packet. The word čerešňa (cherry in Slovak) shows that the text is encoded to UTF-8 bytes and decoded back. The packet length is measured in bytes, not characters. If the server is not running, receive throws SocketTimeoutException after two seconds.

We start the server first and then run the client in another terminal. The server logs all three packets from the same client port.

$ java UdpUpperServer.java
UDP server listening on port 8082
/127.0.0.1:43503: falcon
/127.0.0.1:43503: sky
/127.0.0.1:43503: čerešňa

$ java UdpUpperClient.java
falcon -> FALCON
sky -> SKY
čerešňa -> ČEREŠŇA

Source

Java Socket, Java ServerSocket, Java DatagramSocket, Java DatagramPacket

In this article we have done network programming in Java with sockets. We have written TCP clients for the daytime, whois, and HTTP protocols, set socket timeouts, created single-client and concurrent TCP servers, and exchanged datagrams over UDP. See also the Java HttpClient, Java GET/POST request, Java BufferedReader, Java InputStreamReader, and Java Thread articles.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Java tutorials.