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 |
|
Creates a server socket that isn’t bound to any 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 |
|
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 |
|
Binds this server socket to the specified address. |
|
Closes the server socket. |
|
Gets the address to which the server socket is connected. |
|
Indicates whether the server socket is bound to a port. |
|
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.