Java Reference
In-Depth Information
conform to in order to communicate. If the port you try to open is being used when you try to
instantiate your
ServerSocket
, then an
IOException
is thrown. If the socket is successfully cre-
ated, the server listens on that port for incoming connections by using the
accept
method.
The
ServerSocket.accept
method returns the client socket that is connected to the client.
Figure 7-3.
Lifecycle of a multithreaded socket server
■
Note
More accurately, if the port you try to open is already being used when you try to instantiate your
ServerSocket
connection, a
BindException
will be thrown. However, the constructor for
ServerSocket
only specifies the superclass of
BindException
(
IOException
) will be thrown, as other exceptions may
also be thrown during construction.
Next, the server opens readers and writers on the socket and communicates with the
client by writing and reading to the socket. The
ServerSocket.accept
method blocks the port
until a client connects, and then it returns a
Socket
object. The socket connection is then used
to execute the client request, and the connection can be closed for that client.