关于NIO进行socket通信的一个不解的地方
服务器端代码:
|
客户端代码:
|
我已经和网上的N多类似程序对照过了,但是我就是弄不明白,为什么客户端明明只是发送了三次数据,而服务器端却会不停地执行write和read操作呢?不是应该执行一次之后就完了的吗?
服务器端代码:
|
客户端代码:
|
我已经和网上的N多类似程序对照过了,但是我就是弄不明白,为什么客户端明明只是发送了三次数据,而服务器端却会不停地执行write和read操作呢?不是应该执行一次之后就完了的吗?
你仔细看过用到的类的说明吗?其中java.nio.channels.SelectionKey是这么说明的:
A selection key is created each time a channel is registered with a selector. A key remains valid until it is cancelled by invoking its cancel method, by closing its channel, or by closing its selector. Cancelling a key does not immediately remove it from its selector; it is instead added to the selector's cancelled-key set for removal during the next selection operation. The validity of a key may be tested by invoking its isValid method.
也就是说一个key用完不用了要调用cancel方法,或者关闭他的channel或selector,你的server代码中if(key.isAcceptable)处理完毕后应该关闭该key,要不下次循环认为它是valid还会再次符合key.isAcceptable。另外,一旦该key已经cancel掉了,下面再判断isReadable或者isWritable时要提前判断isValid或者干脆把你这个if逻辑改成
if (key.isAcceptable()) {
...
key.cancel();
} else if (key.isReadable()) {
...
key.cancel();
} else if (key.isWritable()) {
...
key.cancel();
}