Java Reference
In-Depth Information
program places this code within a (programmer-defi ned) method called closeSocket
(which takes the Socket object as its single argument). The code to handle the com-
munication breakdown as described above is shown here:
socket = socketChannel.socket();
if (numBytes==-1)
Now that all the required steps for implementation of a non-blocking server have
been covered, this section will fi nish with an example that brings together all those
individual steps…
This example is the multiplexing equivalent of MultiEchoServer from Sect. 3.3 and
will allow you to compare the coding requirements of the multithreading approach
with those of the multiplexing approach. The code for the equivalent client is not
shown, since this (of course) will be identical to that shown for MultiEchoClient . As
before, the server simply echoes back all transmissions from the client(s).
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
public class MultiEchoServerNIO
private static ServerSocketChannel
private static fi nal int PORT = 1234;
private static Selector selector;
Above Selector used both for detecting new
connections (on the ServerSocketChannel) and for
detecting incoming data from existing connections
(on the SocketChannel).
public static void main(String[] args)
ServerSocket serverSocket;
System.out.println("Opening port…\n");
Search WWH ::

Custom Search