Socket_OverView2
 
Constructing Server Socket
try {
    ServerSocket ss = new ServerSocket(80);
 }
 catch (IOException e) {
    System.err.println(e);
 }
OR
try {
  ServerSocket httpd = new ServerSocket(80, 50);
}
catch (IOException e) {
  System.err.println(e);
}
OR]
try {
 InetAddress ia = InetAddress.getByName("199.1.32.90");
 ServerSocket ss = new ServerSocket(80, 50, ia);
}
catch (IOException e) {
 System.err.println(e);
}
 
  • On a server with multiple IP addresses, the getInetAddress() method tells you which one this server socket is listening to.

    public InetAddress getInetAddress()

  • The getLocalPort() method tells you which port you're listening to.
  • public int getLocalPort()
  • When a ServerSocket object is created, it attempts to bind to the port on the local host given by the port argument.
  • If another server socket is already listening to the port, then a java.net.BindException, a subclass of IOException, is thrown.
  • No more than one process or thread can listen to a particular port at a time. This includes non-Java processes or threads.
  • For example, if there's already an HTTP server running on port 80, you won't be able to bind to port 80.
  • On Unix systems (but not Windows or the Mac) your program must be running as root to bind to a port between 1 and 1023.
  • 0 is a special port number. It tells Java to pick an available port.
  • The getLocalPort() method tells you what port the server socket is listening on. This is useful if the client and the server have already established a separate channel of communication over which the chosen port number can be communicated.
  • The accept() and close(), tenders basic functionalities of a server socket
  • A server socket once close can't be reopened
     
    try {
     ServerSocket ss = new ServerSocket(2345);
     Socket s = ss.accept();
     Writer out = new BufferedWriter
    (new OutputStreamWriter(s.getOutputStream()));
     out.write("Hello There!\r\n");
     out.write("Goodbye now.\r\n");
     out.flush();
     s.close();
    }
    catch (IOException e) {
     System.err.println(e);
    }
Setting Server Socket Options:
  • public synchronized void setSoTimeout(int timeout) throws SocketException
  • public synchronized int getSoTimeout() throws IOException
  • public static synchronized void setSocketFactory(SocketImplFactory
    fac) throws IOException