我有一个线程,女巫正在测试一个socket通道选择器。如果一个套接字通道被连接,并且可以被读取,那么它应该启动一个消息处理程序线程,在这个线程中读取和处理消息。我需要启动处理程序线程,因为有很多事情要做,它需要时间来完成它们。
主线程:
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();
}
}
阅读功能:
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();
}
}
问题是,当处理程序线程执行时,给定的socketchannel已经关闭。如果我不运行线程,只有我调用run()方法,那么套接字没有关闭,所以我认为主线程迭代正在关闭给定的SocketChannel。有人能帮我找出一个解决办法,我怎么能保持SocketChannel打开,直到处理程序线程停止工作?
编辑
也许我应该"注销"SocketChannel从选择器,开始新的线程之前…如何从选择器中注销socketChannel ?
好了,我找到解决办法了…所以,我们应该从Selector中注销SocketChannel。这可以通过调用key.cancel()函数实现。