您的位置:首页 > 其它

一个简单的NIO实例

2011-09-26 17:07 176 查看
public class TestNio {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress("192.168.27.48", 7777));
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true){
int n = selector.select();
if(n > 0){
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey k = ite.next();
ite.remove();
if(k.isAcceptable()){
SocketChannel s = ((ServerSocketChannel)k.channel()).accept();
s.configureBlocking(false);
System.out.println("accept:" + s.socket().getPort() + " s:" + s);
s.register(selector, SelectionKey.OP_WRITE);
}else if(k.isReadable()){
SocketChannel sc = (SocketChannel) k.channel();
ByteBuffer dst = ByteBuffer.allocate(1024);
sc.read(dst);
System.out.println("str:" + dst.toString());
sc.keyFor(selector).cancel();
sc.keyFor(selector).interestOps(SelectionKey.OP_WRITE);
}else if(k.isWritable()){
SocketChannel sc = (SocketChannel) k.channel();
ByteBuffer b = ByteBuffer.allocate(12);
b.put(new String("repaly").getBytes("utf-8"));
b.flip();
sc.write(b);
sc.keyFor(selector).interestOps(SelectionKey.OP_READ);
}
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string dst class