netty/demo1/src/main/java/cn/bunny/file_dir/ServerDemo.java

77 lines
2.7 KiB
Java
Raw Normal View History

2024-05-23 10:08:25 +08:00
package cn.bunny.file_dir;
import lombok.extern.slf4j.Slf4j;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
@Slf4j
public class ServerDemo {
// 阻塞模式下只能接受一个连接
public static void main(String[] args) throws IOException {
// 创建Selector
Selector selector = Selector.open();
// 创建服务器
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
SelectionKey selectionKey = serverSocketChannel.register(selector, 0, null);
// 只关注channel时间
selectionKey.interestOps(SelectionKey.OP_ACCEPT);
System.out.println(STR."注册时的key:\{selectionKey}");
// 模拟监听端口
serverSocketChannel.bind(new InetSocketAddress(8080));
while (true) {
selector.select();
// 处理事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
System.out.println(STR."key的值为\{key}");
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel accept = channel.accept();
System.out.println(STR."接受到的值\{accept}");
}
}
}
private static void m1() throws IOException {
// 使用 ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(16);
// 创建服务器
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
// 模拟监听端口
serverSocketChannel.bind(new InetSocketAddress(8080));
// 连接集合
ArrayList<SocketChannel> channels = new ArrayList<>();
while (true) {
SocketChannel accept = serverSocketChannel.accept();
if (accept != null) {
accept.configureBlocking(false);
channels.add(accept);
}
for (SocketChannel channel : channels) {
int read = channel.read(buffer);
// 当read大于0时才去读
if (read > 0) {
buffer.flip();
System.out.println((STR."读取到的内容:\{StandardCharsets.UTF_8.decode(buffer)}"));
buffer.clear();
}
}
}
}
}