日期:2014-05-20 浏览次数:20890 次
while (selector.select() > 0)
{
Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
System.out.println("while out");
while (it.hasNext())
{
System.out.println("while in");
SelectionKey key = (SelectionKey) it.next();
it.remove();
if (key.isAcceptable())
{
System.out.println("Key is Acceptable");
socket = (SocketChannel) ssc.accept();
socket.configureBlocking(false);
socket.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
}
if (key.isReadable()) {
System.out.println("Key is readable");
socket = (SocketChannel) key.channel();
ByteBuffer buf = ByteBuffer.allocate(25);
buf.clear();
socket.read(buf);
buf.flip();
Charset charset = Charset.forName("us-ascii");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
String result = charBuffer.toString();
System.out.println("Receive Data:" + result);
// key.cancel();如果这个注释的话,就会进行无限循环
}
}
public static int sendMessage(SocketChannel client) {
String msg = null;
ByteBuffer bytebuf=ByteBuffer.allocate(1024);
int nBytes = 0;
try {
msg = "It's message from client!";
System.out.println("msg is "+msg);
bytebuf.clear();
bytebuf.put(msg.getBytes());
bytebuf.flip();
nBytes = client.write(bytebuf);
System.out.println("It's message from client!".getBytes().length);
client.close();
} catch (IOException e) {
e.printStackTrace();
}
return nBytes;
}