Java Reference
In-Depth Information
The ServerSocket Class
The java.net.ServerSocket class is used by server applications to obtain a port
and listen for client requests. The ServerSocket class has four constructors:
public ServerSocket(int port) throws IOException. Attempts to create a
server socket bound to the specified port. An exception occurs if the port
is already bound by another application. The port parameter can be 0,
which creates the socket on any free port.
public ServerSocket(int port, int backlog) throws IOException. Similar
to the previous constructor, the backlog parameter specifies how many
incoming clients to store in a wait queue. If the queue is full, clients
attempting to connect to this port will receive an exception. If the value
is 0, the default queue size of the native platform is used.
public ServerSocket(int port, int backlog, InetAddress address) throws
IOException. Similar to the previous constructor, the InetAddress
parameter specifies the local IP address to bind to. The InetAddress is
used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on.
public ServerSocket() throws IOException. Creates an unbound server
socket. When using this constructor, use the bind() method when you
are ready to bind the server socket.
Notice that each of the constructors throws an IOException when something
goes wrong. However, if the ServerSocket constructor does not throw an
exception, it means that your application has successfully bound to the speci-
fied port and is ready for client requests. Here are some of the common meth-
ods of the ServerSocket class:
public int getLocalPort(). Returns the port that the server socket is listen-
ing on. This method is useful if you passed in 0 as the port number in a
constructor and let the server find a port for you.
public Socket accept() throws IOException. Waits for an incoming
client. This method blocks until either a client connects to the server on
the specified port or the socket times out, assuming that the time-out
value has been set using the setSoTimeout() method. Otherwise, this
method blocks indefinitely.
public void setSoTimeout(int timeout). Sets the time-out value for how
long the server socket waits for a client during the accept().
Search WWH ::




Custom Search