ServerSocket Class

Package: java.net

The ServerSocket class lets client programs connect with a server program. When a client connects, the server socket creates a Socket object, which the server can then use to communicate with the client.

Constructors

Constructor

Description

ServerSocket()

Creates a server socket that isn’t bound to any port.

ServerSocket(int port)

Creates a server socket and binds it to the specified port. Then the server socket listens for connection attempts on this port.

Methods

Method

Description

Socket accept()

Listens for connection attempts via the port this socket is bound to. The thread that calls this method waits until a connection is made. Then this method exits, returning a Socket object that can be used to communicate with the client.

void bind(Inet SocketAddress endpoint)

Binds this server socket to the specified address.

void close()

Closes the server socket.

InetAddress getInetAddress()

Gets the address to which the server socket is connected.

boolean isBound()

Indicates whether the server socket is bound to a port.

boolean isClosed()

Indicates whether the server socket is closed.

A server socket is associated with a particular port on a server computer. Thus, it’s common to pass the port number to the ServerSocket class when you instantiate it, as in this example:

int port = 1234;

ServerSocket ss = new ServerSocket(port);

In the preceding example, the server socket is associated with port 1234.

After you create a server socket object, you can call the accept method to wait for a client to connect, like this:

Socket s = ss.accept();

The accept method suspends the thread until a client computer connects, at which time the thread wakes up, and the accept method returns a Socket object that represents the connection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset