Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Hi,
I would really appreciate your help on this one.
I am trying to get a simple server-client working with the nio api.
SERVER
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new java.net.InetSocketAddress(IP, Port));
selector = Selector.open();
server.register(selector, SelectionKey.OP_ACCEPT);
CLIENT
SocketChannel client = SocketChannel.open();
client.configureBlocking(false);
client.connect(new java.net.InetSocketAddress("localhost",8000));
Selector selector = Selector.open();
SelectionKey clientKey = client.register(selector, SelectionKey.OP_CONNECT);
SERVER
while (true) {
int n = selector.select();
Iterator i = selector.selectedKeys().iterator();
while(i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
}
}
This is all the code I have left uncommented in my application.
Here's what happens :
The client terminates, and the server loops forever; the selector.select() returns 1 as long as the server is alive, and the same selectionkey. I would have expected for the key to have been fetched only once, since it is removed, and nothing happens with the channel afterwards.
Just to be sure, I am ending the client like this :
Thread.sleep(10000);
clientKey.cancel();
client.close();
Thank you,
Andrei