Server Sockets in Java
|
|
|
|
| Articles Reviews Java | |
| Written by Phil Harrison | |
| Wednesday, 24 January 2007 | |
|
{mos_sb_discuss:34} From a programmer’s point of view, the main difference between a client and a server has to do with initiation. A client always gets to assume that a server is available.
You can see this assumption at work when you construct a Socket instance: the constructor automatically connects to the specified server’s specified port.
A server, on the other hand, makes itself available and then waits for clients to initiate connections. This is done with an abstraction called a server socket , which in Java is represented by the java.net.ServerSocket class. The most useful form of the ServerSocket constructor is public ServerSocket(int portNumber) The constructor throws IOException if it gets into trouble. To make the new object available for client connections, call its accept() method, which returns an instance of Socket , as shown below: Once a client connects, the accept() method constructs and returns an instance of Socket. The subsequent server code can use the socket’s input and output streams directly for byte communication, or higher-level streams can be chained to support communication of higher-level data. Thus, once a client has connected to the server, writing server code is just like writing client code. The “server’s” phone rings. The moment the “server” picks up the ringing phone, the two people are in identical situations, communicating with identical equipment. In the case of accept() , the necessary resource is the client. Clearly the method can’t proceed until a client appears. In Java, methods block by calling wait() , which puts the current thread in a waiting state as you saw in Chapter 7, “Threads.” In a properly designed program, another thread will eventually detect the presence of the desired resource; that thread will notify the waiting thread. For example, a server might rely on a class called ServiceGiver , which implements java.lang.Runnable . import java.net.*; A server can use the ServiceGiver class like this: try { The thread that calls accept() is almost always waiting for new client connections; it is unavailable only for the brief time required to pass a newly connected socket to a ServiceGiver instance. Powered by jReviews |
|
| Last Updated ( Wednesday, 13 June 2007 ) | |
| < Prev | Next > |
|---|







