Creating a Server and Accepting a Request


public static final short PORT = 9988; ServerSocket server = new ServerSocket(PORT); while ((clientSock = server.accept( )) != null) {     // Process client request }



In this phrase, we use a ServerSocket instance to create a server listening on port 9988. We pass the port that we want the server to listen on to the constructor of the ServerSocket. Once the server socket is created, we call the accept() method to wait for a client connection. The accept() method blocks until a connection with a client is made. When a client connection is made, a new Socket instance is returned.

If a security manager is being used, the security manager's checkAccept() method is called with clientSock.getInetAddress().getHostAddress() and clientSock.getPort() as its arguments to ensure the operation is allowed. This could result in a SecurityException.

The phrases in this chapter all make use of the ServerSocket class. The ServerSocket class is used by a server to wait for and make connections with a client. As seen in this phrase, when you first create a ServerSocket class, you specify a port to listen on for incoming requests. The ServerSocket class itself is not used for communication with a client, but only to establish a connection with the client. When ServerSocket accepts a client connection, a regular Socket instance is returned. The Socket instance is what you use to communicate with the client.

See the related phrase, "Handling Multiple Clients" for information on how you should write your code when you expect to handle many simultaneous client requests.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net