Server Socket Accept Loop

Accept one loopback client with ServerSocket, echo a line back through the socket streams, and close both ends with try-with-resources.

JavaData Fetching

Code

snippet
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
    public static void main(String[] args) throws Exception {
        try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
            int port = server.getLocalPort();
            System.out.println("listening on " + port);

            Thread client = new Thread(() -> {
                try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), port);
                     PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                     BufferedReader in = new BufferedReader(
                             new InputStreamReader(socket.getInputStream()))) {
                    out.println("ping");
                    System.out.println("client got: " + in.readLine());
                } catch (Exception e) {
                    System.out.println("client failed: " + e.getMessage());
                }
            });
            client.start();

            // accept blocks until the client connects
            try (Socket accepted = server.accept();
                 BufferedReader in = new BufferedReader(
                         new InputStreamReader(accepted.getInputStream()));
                 PrintWriter out = new PrintWriter(accepted.getOutputStream(), true)) {
                out.println("echo: " + in.readLine());
            }
            client.join();
        }
    }
}

How it works

Structurally, expect the class Main and nothing else.

Resources live in the try header, so closing is compiler-generated and exception-safe.

What to watch for

  • The toolchain alone is enough — no dependency resolution happens.

Using it in your own code

The run emits 3 labeled sections — listening on, client got:, client failed: — one per step.

Interactive Tools for This Topic

FAQ

What does Server Socket Accept Loop print when run?
No setup needed: run the file and look for labeled lines like `listening on`, `client got:`, `client failed:` in the output.