Java Reference
In-Depth Information
try {
Socket clntSock = sock.accept( );
new Handler(clntSock).start( );
} catch(IOException e) {
System.err.println(e);
}
}
}
To use a thread, you must either subclass Thread or implement Runnable . The Handler
class must be a subclass of Thread for this code to work as written; if Handler instead im-
plemented the Runnable interface, the code would pass an instance of the Runnable into the
constructor for Thread , as in:
Thread t = new Thread(new Handler(clntSock));
t.start( );
But as written, Handler is constructed using the normal socket returned by accept() , and
normally calls the socket's getInputStream() and getOutputStream() methods and holds
its conversation in the usual way. I'll present a full implementation, a threaded echo client.
First, a session showing it in use:
$ java network.EchoServerThreaded
EchoServerThreaded ready for connections.
Socket starting: Socket[addr=localhost/127.0.0.1,port=2117,localport=7]
Socket starting: Socket[addr=darian/192.168.1.50,port=13386,localport=7]
Socket starting: Socket[addr=darian/192.168.1.50,port=22162,localport=7]
Socket ENDED: Socket[addr=darian/192.168.1.50,port=22162,localport=7]
Socket ENDED: Socket[addr=darian/192.168.1.50,port=13386,localport=7]
Socket ENDED: Socket[addr=localhost/127.0.0.1,port=2117,localport=7]
Here, I connected to the server once with my EchoClient program and, while still connec-
ted, called it up again (and again) with an operating system-provided Telnet client. The serv-
er communicated with all the clients concurrently, sending the answers from the first client
back to the first client, and the data from the second client back to the second client. In short,
it works. I ended the sessions with the end-of-file character in the program and used the nor-
mal disconnect mechanism from the Telnet client. Example 16-6 is the code for the server.
Example 16-6. EchoServerThreaded.java
Search WWH ::




Custom Search