Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท I/O and Files

Sockets: Socket and ServerSocket

Reference for java.net.Socket and ServerSocket: open TCP connections, read and write streams, use timeouts, and run a loopback echo server on 127.0.0.1.

A socket is one end of a TCP connection. ServerSocket listens on a port and hands out a Socket for each client that connects with accept(). A client creates new Socket(host, port). Both sides then use the socket's InputStream and OutputStream, and what one side writes the other reads, in order and without loss.

TCP is a byte stream, not a message protocol. There are no message boundaries, so you need your own framing: lines ending in \n, a length prefix, or a fixed size. Most simple programs wrap the streams in a BufferedReader and PrintWriter and exchange text lines.

Java
try (ServerSocket server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
    int port = server.getLocalPort();   // port 0 = pick a free one
}

Try it

Java An echo server and client on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Timeouts and refused connections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class Socket implements Closeable
Socket(String host, int port) throws IOException
Socket(InetAddress address, int port) throws IOException
Socket()                                   // unconnected; call connect(SocketAddress, int timeout)

public class ServerSocket implements Closeable
ServerSocket(int port) throws IOException
ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException
Member Description
Socket accept() (ServerSocket) Blocks until a client connects.
int getLocalPort() (ServerSocket) The bound port, useful after binding to port 0.
void setReuseAddress(boolean) Allows rebinding a port that is in TIME_WAIT.
InputStream getInputStream() / OutputStream getOutputStream() The byte streams of a connected socket.
void connect(SocketAddress, int timeoutMs) Connects with a timeout.
void setSoTimeout(int ms) Read (or accept) timeout; 0 means wait forever.
void shutdownOutput() / shutdownInput() Half-close: tells the peer "no more data" but keeps reading.
void setTcpNoDelay(boolean), setKeepAlive(boolean) Socket options.
boolean isConnected(), isClosed() State flags; neither detects a dead peer.

Throws: UnknownHostException, ConnectException (refused), SocketTimeoutException (a subclass of InterruptedIOException), BindException (port in use), SocketException ("Connection reset", "Socket closed"); all are IOExceptions.

Usage notes

  • Bind to loopback in tests. InetAddress.getLoopbackAddress() keeps the server reachable only from this computer. new ServerSocket(port) listens on every interface.
  • Port 0 asks the operating system for a free port, which avoids "address already in use" in tests.
  • Flush your writes. Output may sit in a buffer. PrintWriter needs autoFlush and println, or an explicit flush().
  • End of stream. readLine() returns null and read() returns -1 when the peer closes or half-closes. Use shutdownOutput() to say "I am done sending" while waiting for the reply.
  • One thread per connection is the simple model; with virtual threads (Java 21+) it scales to many thousands of blocking connections.
  • Always set timeouts on real networks. A read without setSoTimeout can block forever on a silent peer.
  • Always specify the charset for text, as in the example. The platform default is UTF-8 from Java 18, but older runtimes differ.
  • Closing a socket closes its streams and vice versa. Use try-with-resources on both sides.
  • No TLS here. Use SSLSocketFactory for encrypted connections; for HTTP, prefer HttpClient.
  • Sandbox note: the examples here use only 127.0.0.1; outgoing connections to other hosts are blocked on this site.