---
title: "SocketChannel "
author: "AAries"
date: "2011-08-08T19:28:24Z"
tags: []
categories: ["编程语言"]
slug: "socketchannel"
draft: false
lastmod: "2011-08-08T19:28:24Z"
id: 1142915
url: "https://ati000.iteye.com/blog/1142915"
---

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();
     }