SocketChannel

1.SocketChannel 客户端与 ServerSocketChannel 服务器端通信

2.客户端使用SocketChannel的connect方法连接服务器时,服务器会收到一个可接受的包。建立连接,同时在此时设置下一次的包是可读或是可写等等。

3.如果服务器端指定为可读,而客户端指定为可写,会出异常。反之亦然。

4.如果在服务器端为指定下次接受的包的读写性,则既不会读也不会写。

5.在读buffer前必须flip();

遍历一个selectionkey集合。
e.g. SocketChannel sk = (SocketChannel)SelectionKey.channel();
     ByteBuffer buf = (buffer)selectionKey.attachment();
     buf.clear();
     long readNum = sk.read(buf);
     if(readNum == -1)
     {
       /*buf为空*/
     }
     else
     {
buf.flip();
        String receive = Charset.forName("UTF-16").newDecoder().decode(buff).toString();
     }

你可能感兴趣的:(SocketChannel)