csusky

常用链接

统计

最新评论

2009年11月10日 #

异步IO的关闭事件

JAVA SOCKET只定义了四种事件

public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;

是没有关闭事件的,我们怎么判断一个连接是否关闭呢?
如果你的selector注册了一个OP_READ事件,那么在连接关闭的时候将会产生一个OP_READ事件
也就是说本来阻塞的selector此时将会被唤醒,但是如果试图在此事件的通道中读取数据将会返回-1
如下:

Set<SelectionKey> readyKeys = selector.selectedKeys();

= readyKeys.iterator()

SelectionKey key 
= (SelectionKey)i.next();

if (operation == SelectionKey.OP_READ &&
                         key.isReadable())
                
{
                    ReadableByteChannel incomingChannel 
= (ReadableByteChannel)key.channel(); 
//此时将会得到-1,表明该链接已关闭
int n = incomingChannel.read(readBuffer);
}
此时我们需要取消该KEY 如下:
if (n == -1)
            
{
                key.cancel();
                  //关闭输入输出 
                  sc.socket().shutdownOutput();
                  sc.socket().shutdownInput();
                   //关闭SOCKET
                   sc.socket().close();
                  //关闭通道
                   incomingChannel.close();
            }

posted @ 2009-11-10 22:28 晓宇 阅读(391) | 评论 (1)编辑 收藏