-
problem with java nio
Hi everyone,
I am having problems with setting up the communication between a server and a client with the java.nio api.
I am using a selector, a serversocketchannel, and a socketchannel for the client -- so the mechanism is based on SelectionKeys.
The problem, as it seems to me, is that once the client connects to the server, and the server receives the SelectionKey - acceptable type, and after i invoke remove on the selector's iterator for this specific key, THE SELECTOR.SELECT() METHOD KEEPS RETURNING THE SAME KEY.
I will give anyone who helps me on this one my entire kingdom !
Here's some code :
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);
while (true) {
n = selector.select();
Iterator i = selector.selectedKeys().iterator(); while(i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
i.remove();
log.info("selection [process :::: " + n + " " + key);
}
}
n is always 1 - the key is the same object - the same reference.
Here's the client :
Selector selector = Selector.open();
SocketChannel client = SocketChannel.open();
client.configureBlocking(false);
client.connect(new java.net.InetSocketAddress("localhost",8000));
while (!client.finishConnect())
;
SelectionKey clientKey = client.register(selector, SelectionKey.OP_READ);
Thread.sleep(10000);
clientKey.cancel();
client.close();
The client does its bussiness and gracefully quits.
The server hangs on in an infinite loop, and it always finds the same key after selector.select.
Thank you,
Andrei
-
When NIO came out, I spent a huge amount of time trying to get it to work. I never made my code work. And lots of people have problems. I think that the NIO design is simply too complex.
But there is a solution. Check out Apache's MINA.
Its an easy to use framework that uses NIO and has tons of features.
Apache MINA - Index
-
Thank you for your reply. I appreciate your help, and under normal circumstances I would have probably followed your advice. But, I have to use this api and not a wrapper. This is because the project is one of my faculty homeworks, so I am doomed to find a solution.
-
Doomed is right. Start by ignoring the selector portion of the design. Selectors are useful for big servers, but you need to get the underlying ServerSocketChannel and SocketChannel communicating first. In reality, that's enough for most applications.
As best I understand, the selector functionality allows you to register channels with the selector, and the selector monitors the channels. This would be most useful with multiple channels being handled by a single application. The selector simply tells the application what the latest event is. Once you have the channel logic working, I don't think the Selector will be too bad, just unnecessary.