package org.example;
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;
//TIP To Run code, press or
// click the icon in the gutter.
public class Main {
public static void main(String[] args)throws IOException {
//TIP Press with your caret at the highlighted text
// to see how IntelliJ IDEA suggests fixing it.
Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress(9080));
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set selectedKeys = selector.selectedKeys();
Iterator iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isAcceptable()) {
registerClient(selector, serverSocket);
}
if (key.isReadable()) {
handleRead(key);
}
iter.remove();
}
}
}
private static void registerClient(Selector selector, ServerSocketChannel serverSocket)throws IOException {
SocketChannel client = serverSocket.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
System.out.println("Accepted connction from " + client);
}
private static void handleRead(SelectionKey key)throws IOException {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = client.read(buffer);
if (read == -1) {
client.close();
return;
}
buffer.flip();
// 处理从客户端读取的数据
System.out.println("Received: " +new String(buffer.array(), 0, read));
buffer.clear();
}
}