我正在编写一个服务器来在客户端之间交换消息。一个有待解决的问题是如何在客户端关闭时释放通道。我所做的是启动一个监控线程,在该线程中监控所有客户端映射,如果在尝试对其进行 write() 时检测到异常,我会尝试 remove() 一个通道。但是,在关闭客户端后,监控线程中的 write() 方法不会抛出异常,因此永远不会释放无用的通道。有人知道为什么吗?
public class ServerMonitor extends Thread{
private Map<String, SocketChannel> allClients;
private Set set;
private Iterator it;
private Entry entry;
private SocketChannel channel;
private ByteBuffer buf;
public ServerMonitor(Map<String, SocketChannel> allClients) {
this.allClients = allClients;
buf = ByteBuffer.allocateDirect(10);
byte b = 0;
buf.put(b);
buf.flip();
}
public void run(){
while(true) {
if(!allClients.isEmpty()) {
set = allClients.entrySet();
it = set.iterator();
while(it.hasNext()) {
entry = (Entry) it.next();
channel = (SocketChannel) entry.getValue();
try{
channel.write(buf);
} catch(Exception e) {
allClients.remove(entry.getKey());
//set.remove(entry);
}
}
}
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}