package linag.test.dubbo.core.netty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NioServer {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(11000));
//注册一个ServerSocketChannel并监听accept事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT );
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(11001));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT );
for(;;) {
// 当注册事件到达时,方法返回,否则该方法会一直阻塞
int nReadyChannels = selector.select();
System.out.println("nReadyChannels:" + nReadyChannels);
if(nReadyChannels == 0 ) {
continue;
}
// 获得selector中选中的相的迭代器,选中的相为注册的事件
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
//如果有客户端连接进来
if(selectionKey.isAcceptable()) {
ServerSocketChannel selectedServerSocketChannel = (ServerSocketChannel)selectionKey.channel();
SocketChannel channel = selectedServerSocketChannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
}else if(selectionKey.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(100);
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
while (socketChannel.read(buffer) > 0) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.println((char)buffer.get());
}
buffer.clear();
}
}
}
iterator.remove();
}
}
}
NioServer
最新推荐文章于 2024-04-10 09:58:12 发布