Java Reference
In-Depth Information
SocketChannel socketChannel;
Socket socket;
socketChannel = serverSocketChannel.accept();
socketChannel.confi gureBlocking(false);
socket = socketChannel.socket();
System.out.println("Connection on "
+ socket + ".");
//Register SocketChannel for receiving data…
socketChannel.register(selector,
SelectionKey.OP_READ);
//Avoid re-processing this event as though it
//were a new one (next time through loop)…
selector.selectedKeys().remove(key);
}
private static void acceptData(SelectionKey key)
throws IOException
{//Accept data from existing connection.
SocketChannel socketChannel;
Socket socket;
ByteBuffer buffer = ByteBuffer.allocate(2048);
//Above used for reading/writing data from/to
//SocketChannel.
socketChannel = (SocketChannel)key.channel();
buffer.clear();
int numBytes = socketChannel.read(buffer);
System.out.println(numBytes + " bytes read.");
socket = socketChannel.socket();
if (numBytes==-1)
//OP_READ event also triggered by closure of
//connection or error of some kind. In either
//case, numBytes = -1.
{
//Request that registration of this key's
//channel with its selector be cancelled…
key.cancel();
System.out.println("\nClosing socket "
+ socket + "…");
closeSocket(socket);
}
else
{
try
Search WWH ::




Custom Search