Java Reference
In-Depth Information
The channels associated with Socket s and ServerSocket s are, unsurprisingly, called
SocketChannel s and ServerSocketChannel s respectively. Classes SocketChannel
and ServerSocketChannel are contained in package java.nio.channels . By default,
the sockets associated with such channels will operate in blocking mode, but may
be confi gured as non-blocking sockets by calling method confi gureBlocking with an
argument of false . This method is a method of the channel classes and needs to
be called on a channel object before the associated socket is created. Once this has
been done, the socket itself may be generated by calling method socket on the chan-
nel socket. The code below shows these steps. In this code and elsewhere in this
section, the prior declaration of Socket , SocketChannel, ServerSocket and
ServerSocketChannel objects with names socket , socketChannel , serverSocket and
serverSocketChannel respectively is assumed. Note that a ServerSocketChannel
object is created not via a constructor, but via static method open of the
ServerSocketChannel class. This generates an instance of a platform-specifi c sub-
class that is hidden from the programmer.
serverSocketChannel =;
serverSocketChannel.confi gureBlocking(false);
serverSocket = serverSocketChannel.socket();
//The lines below will occur rather later in the
//program, of course.
socketChannel = serverSocketChannel.accept();
socketChannel.confi gureBlocking(false);
socket = socketChannel.socket();
Once the ServerSocketChannel and ServerSocket objects have been created, the
ServerSocket object needs to be bound to the port on which the server is to be run. This
involves the creation of an object of class InetSocketAddress , which is another class
introduced in J2SE 1.4 and is defi ned in package . The lines required to create
the InetSocketAddress object and bind the ServerSocket object to the port are shown
below. The pre-declaration of a constant PORT holding the port number is assumed.
InetSocketAddress netAddress =
new InetSocketAddress(PORT);
serverSocket.bind(netAddress); //Bind socket to port.
It is now appropriate to create an instance of class Selector , which is another of
the classes in package java.nio.channels . This object will be responsible for monitor-
ing both new connections and the transmission of data from and to existing connec-
tions. Each channel (whether SocketChannel or ServerSocketChannel ) must register
with the Selector object the type of event in which the channel is interested via
method register . There are four static constants of class SelectionKey (package java.
nio.channels ) that are used to identify the type of event that may be monitored:
Search WWH ::

Custom Search