java.net.ServerSocket is a class for implementing server sockets. ServerSockets can be created unbound, or bound to a particular port. In either case, the constructor may throw an IOException, which may be thrown when attempting to open the socket.
The most important method on a server socket is accept(), which listens for a connection to be made to the socket and accepts it.
Example code (notice the interplay between the
ServerSocket and
Socket classes):
import java.net.ServerSocket;import java.net.BindException;ServerSocket listenSocket = null;try {listenSocket = new ServerSocket(serverPort);while(true) {// listen for and accept incoming connection
Socket clientSocket = listenSocket.accept();// do something
}} catch (BindException bindEx) { // error message to say server is already running on serverPortSystem.exit(0);}
The socket class abstracts the concept of an
endpoint of communication between
two machines. A nice visual analogy of the socket idiom is the
probe-and-drogue method of aerial refuelling used by the USAF. Pictures can be seen on
aerospaceweb.
SSLServerSocket is a special instance of ServerSocket; these sockets aer generally created by an
SSLServerSocketFactory.