Tech and Media Labs
This site uses cookies to improve the user experience.

Java Networking: ServerSocket

Jakob Jenkov
Last update: 2014-06-25

In order to implement a Java server that listens for incoming connections from clients via TCP/IP, you need to use a . In case you prefer to use Java NIO instead of Java Networking (standard API), then you can also use a ServerSocketChannel instead of the

Creating a ServerSocket

Here is a simple code example that creates a ServerSocket that listens on port 9000:

ServerSocket serverSocket = new ServerSocket(9000);

Listening For Incoming Connections

In order to accept incoming connections you must call the ServerSocket.accept() method. The accept() method returns a Socket which behaves like an ordinary Java Socket. Here is how that looks:

ServerSocket serverSocket = new ServerSocket(9000);

boolean isStopped = false;
    Socket clientSocket = serverSocket.accept();

    //do something with clientSocket

Only one incoming connection is opened for each call to the accept() method.

Additionally, incoming connections can only be accepted while the thread running the server has called accept(). All the time the thread is executing outside of this method no clients can connect. Therefore the "accepting" thread normally passes incoming connections (Socket's) on to a pool of worker threads, who then communicate with the client. See the tutorial trail Java Multithreaded Servers for more information on multithreaded server design.

Closing Client Sockets

Once a client request is finished, and no further requests will be received from that client, you must close that Socket, just like you would close a normal client Socket. This is done by calling:


Closing Server Sockets

Once the server is to shut down you need to close the ServerSocket. This is done by calling:


Jakob Jenkov

Copyright  Jenkov Aps
Close TOC