TCP/IP Server Sockets

The ServerSocket class creates servers that listen for client programs to connect to them on published ports. The ServerSocket class is designed to be a "listener," which waits for clients to connect before doing anything.

Here are three of its constructors:

ServerSocket(int port) throws IOException
Creates server socket on the specified port with a queue length of 50.
ServerSocket(int port, int maxQueue) throws IOException
Creates a server socket on the specified port with a maximum queue length of maxQueue.
ServerSocket(int port, int maxQueue, InetAddress localAddress) throws IOException
Creates a server socket on the specified port with a maximum queue length of maxQueue. On a multihomed host, localAddress specifies the IP address to which this socket binds.

accept() method from ServerSocket is a blocking call that will wait for a client to initiate communications and return with a Socket that is then used for communication with the client.


import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainClass {

  public static void main(String args[]) {
    try {

      int port = 5555;
      ServerSocket ss = new ServerSocket(port);

      while (true) {
        // Accept incoming requests
        Socket s = ss.accept();

        // Write result to client
        OutputStream os = s.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeInt(100);

        s.close();
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}
Home 
  Java Book 
    Networking  

ServerSocket:
  1. TCP/IP Server Sockets
  2. ServerSocket: accept()
  3. ServerSocket: bind(SocketAddress endpoint)
  4. ServerSocket: getLocalPort()
  5. ServerSocket: readUTF() and writeUTF(String str)
  6. ServerSocket: setSoTimeout(int timeout)