Java Reference
In-Depth Information
ServerSocket(int port, int backlog) is equivalent to the pre-
vious constructor, but it also lets you specify the maximum queue length by
passing a positive integer to backlog .
ServerSocket(int port, int backlog, InetAddress
bindAddr) isequivalenttothepreviousconstructor,butitalsoletsyouspe-
cifyadifferentIPaddresstowhichtheserversocketbinds.Thisconstructoris
usefulformachinesthathavemultipleNICsandyouwanttolistenforconnec-
tion indications on a specific NIC.
Aftercreatingaserversocket,aserverapplicationentersaloopwhereitfirstinvokes
ServerSocket 's Socket accept() methodtolistenforaconnectionindication
andreturna Socket instancethatletsitcommunicatewiththeassociatedclientsocket.
Itthencommunicateswiththeclientsockettoperformsomekindofprocessing.When
processingfinishes,theserversocketcallstheclientsocket's close() methodtoter-
minate its connection with the client.
Note ServerSocket declares a void close() method for closing a server
socket before terminating the server application.
The following example demonstrates how to create a server socket that's bound to
port 1500 on the current host, listen for incoming connection indications, return their
sockets,performworkonthosesockets,andclosethesockets—exceptionsareignored
for brevity:
ServerSocket ss = new ServerSocket(1500);
while (true)
{
Socket socket = ss.accept();
// obtain socket input/output streams and communicate
with socket
socket.close();
}
The accept() method call blocks until a connection indication is available, and
then returns a Socket object so that the server application can communicate with its
associated client. The socket is closed after this communication takes place.
Thisexampleassumesthatsocketcommunicationtakesplaceontheserverapplica-
tion'smainthread,whichisaproblemwhenprocessingtakestimetoperformbecause
serverresponsetimetoincomingconnectionindicationsdecreases.Tospeedupthisre-
Search WWH ::




Custom Search