A Java application can open a single Socket on a port and open an InputStream and OutputStream just like the client, but in general, a server will want to be able to open multiple sockets to establish communication with a number of clients at the same time.
|
The ServerSocket class allows multiple sockets:
-
ServerSocket s = new ServerSocket(port);
|
Then the Java server application can use the accept method to open a socket for each client which tries to open a socket on the port:
-
Socket client = s.accept();
|
Typically, a server main program would be waiting to accept a client. When a client tries to establish a socket, the accept proceeds. Then the server would spawn a thread to handle that one socket, opening input and output streams as necessary and communicating with the client.
|