Name
ServerSocket
Synopsis
This class is used by servers to listen
for connection requests from clients. Before you can use a
ServerSocket
, it must be
bound to the local network address that it is to
listen on. All of the ServerSocket( )
constructors
except for the no-argument constructor create a server socket and
bind it to the specified local port, optionally specifying a
“connection backlog” value: this is
the number of client connection attempts that may be queued up before
subsequent connection attempts are rejected.
In Java 1.4 and later, the no-argument ServerSocket(
)
constructor allows you to create an unbound socket. Doing
this allows you to bind the socket using the bind(
)
method which uses a SocketAddress
object rather
than a port number. It also allows you to call
setReuseAddress(
)
,
which is only useful when done before the socket is bound. Call
isBound( )
to
determine whether a server socket has been bound. If it has, use
getLocalSocketAddress(
)
or
getLocalPort( )
and getInetAddress(
)
to obtain the local address it is bound to.
Once a ServerSocket
has been bound, you can call the accept( )
method
to listen on the specified port and block until the client requests a
connection on the port. When this happens, accept(
)
accepts the connection, creating and returning a
Socket
the server can use to communicate with the
client. A typical server starts a new thread to handle the
communication with the client and calls accept( )
again to listen for another connection. ...
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.