30分钟学会NIO -- socket

server端:

public class NIOServer {
private int i = 1;
private Selector selector = null;
private SocketChannel client = null;

public NIOServer(int port) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.socket().bind(new InetSocketAddress(port));
selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
}

private void listen() throws Exception {
while(true) {
int i = selector.select();
Set<SelectionKey> selectedKeys  = null;
if(i>0){
selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while(iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
handleKey(key);
}
}

}
}


private void handleKey(SelectionKey key) throws Exception {
if(key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
client = ssc.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}else if(key.isReadable()) {
ByteBuffer bb = ByteBuffer.allocate(1023);
client.read(bb);
System.out.println("server读:"+new String(bb.array(),0,bb.position()));
client.register(selector, SelectionKey.OP_WRITE);
}else if(key.isWritable()) {
ByteBuffer bb = ByteBuffer.allocate(1024);
bb.put(("dataFormServer"+i++).getBytes());
bb.flip();
client.write(bb);
client.register(selector,SelectionKey.OP_READ);
}
}

public static void main(String[] args) throws Exception {
new NIOServer(7080).listen();
}
}


client端:

public class NIOClient {
private static int j = 1;
public static void main(String[] args) throws Exception {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("127.0.0.1",7080));
Selector selector = Selector.open();
sc.register(selector, SelectionKey.OP_CONNECT);
while(true) {
int i = selector.select();
if(i>0) {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while(iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();///与下面注释关联
if(key.isConnectable()) {
if(sc.isConnectionPending()) {
sc.finishConnect();
sc.register(selector, SelectionKey.OP_WRITE);
}
}else if(key.isWritable()) {
ByteBuffer bb = ByteBuffer.allocate(1024);
bb.put(("dataFromClient:"+j++).getBytes());
bb.flip();
sc.write(bb);//与上面注释关联,如果remove,则不会注销,因为只会注销set中有的集合
sc.register(selector, SelectionKey.OP_READ);
}else if(key.isReadable()) {
ByteBuffer bb = ByteBuffer.allocate(1024);
sc.read(bb);
System.out.println("client 读:"+new String(bb.array(),0,bb.position()));
sc.register(selector,SelectionKey.OP_WRITE);
}
}
}
}
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值