I have a thread, witch is testing a socketchannel selector. If a socketchannel is connected, and can be read, it should start a message handler thread, where the message is read, and handled. I need to start the handler thread, because there have a lot to do, and it needs time to finish them.
main thread:
while (true) {
try {
// Wait for an event one of the registered channels
this.selector.select();
// Iterate over the set of keys for which events are available
Iterator selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
// Check what event is available and deal with it
if (key.isAcceptable()) {
this.accept(key);
}
if (key.isReadable()) {
this.read(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
read function:
private void read(SelectionKey key) throws IOException {
// For an accept to be pending the channel must be a server socket channel.
SocketChannel clientSocketChanel = (SocketChannel) key.channel();
WebCommandHandler commands = new WebCommandHandler(clientSocketChanel);
if (clientSocketChanel.isConnected()) {
Thread cThread = new Thread(commands);
cThread.setName("Message handler");
cThread.start();
}
}
The problem is, when the handler thread is executed, the given socketchannel is already closed. If i don't run the thread, only i'm calling the run() method, then the socket isn't closing, so I think the main thread iteration is closing the given SocketChannel. Can somebody help me figuring out a workaround, how can i keep the SocketChannel opened, until the handler thread stops working?
EDIT
Probably i should "unregister" the SocketChannel from the selector, before starting the new thread... How can i unregister a socketChannel from a Seelctor?