public static void main(String[] args) throws IOException {
// 创建select
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
// 注册 select和channel联系
// SelectionKey是事件发生后,可以得到事件和哪个channel的事件
// 四中事件
// accept -连接请求时触发
// connect -连接一旦建立触发
// read -可读事件
// write -可写事件
SelectionKey sscKey = ssc.register(selector, 0, null);
// 只关注accept事件
sscKey.interestOps(SelectionKey.OP_ACCEPT);
System.out.println("register key:"+sscKey);
ssc.bind(new InetSocketAddress(8888));
while (true){
// 没有事件,则阻塞线程,歇着;有事件才会恢复
selector.select();
// 处理事件,包含了所有发生的事件
// selector会向集合中添加key,但是不会主动删除事件
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
System.out.println("key:"+key);
if(key.isAcceptable()){
try {
// 事件不处理会一直加入事件
ServerSocketChannel channel = (ServerSocketChannel)key.channel();
// 没有连接建立会返回null
SocketChannel sc = channel.accept();
sc.configureBlocking(false);
ByteBuffer bf = ByteBuffer.allocate(2);
SelectionKey scKey = sc.register(selector, 0, bf);
scKey.interestOps(SelectionKey.OP_READ);
System.out.println("sc, "+sc);
// 一定要删除处理的事件
iterator.remove();
}catch (Exception e){
// 强制断开,关闭连接
key.cancel();
}
}else if(key.isReadable()){
try {
SocketChannel readChannel = (SocketChannel)key.channel();
ByteBuffer buffer1 = (ByteBuffer)key.attachment();
int read = readChannel.read(buffer1);
if(read == -1){
// 正常断开,也会触发一次读事件
key.cancel();
}else {
split(buffer1);
if(buffer1.position() == buffer1.limit()){
ByteBuffer newBuffer = ByteBuffer.allocate(buffer1.capacity()*2);
buffer1.flip();
newBuffer.put(buffer1);
key.attach(newBuffer);
}
}
iterator.remove();
}catch (Exception e){
}
}
}
}
}
private static void split(ByteBuffer source) {
source.flip();
for(int i=0;i<source.limit();i++){
//
if(source.get(i)=='\n'){
int length = i+1-source.position();
ByteBuffer target = ByteBuffer.allocate(length);
for(int j=0;j<length;j++){
target.put(source.get());
}
target.flip();
while (target.hasRemaining()){
char b = (char)target.get();
System.out.print(b);
}
System.out.println();
}
}
source.compact();
}
nio编程service
于 2022-02-10 18:04:11 首次发布