public class NIOServer {
private ServerSocketChannel serverSocketChannel;
private Selector selector;
private static final int PORT = 1212;
public NIOServer() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("localhost",PORT));
serverSocketChannel.configureBlocking(false);
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void listen() throws IOException {
while (true) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("accept new conn: " + socketChannel.getRemoteAddress());
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
readData(key);
}
iterator.remove();
}
}
}
private void readData(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int readBytes = 0;
try {
readBytes = socketChannel.read(buffer);
if (readBytes > 0) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
String body = new String(bytes, StandardCharsets.UTF_8);
sendMessageToAll(socketChannel.getRemoteAddress() + "==>" + body, socketChannel);
if ("quit".equals(body)) {
key.cancel();
socketChannel.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessageToAll(String body, SocketChannel self) throws IOException {
System.out.println(body);
for (SelectionKey key : selector.keys()) {
Channel targetChannel = key.channel();
if (targetChannel instanceof SocketChannel && targetChannel != self) {
SocketChannel dest = (SocketChannel)targetChannel;
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
buffer.put(body.getBytes(StandardCharsets.UTF_8));
buffer.flip();
dest.write(buffer);
}
}
}
public static void main(String[] args) throws IOException {
new NIOServer().listen();
}
}
public class NIOClient {
private SocketChannel socketChannel;
private volatile boolean isClosed = false;
public NIOClient() throws IOException {
socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("localhost",1212));
}
public void start() {
new Thread(()->{
try {
Selector selector = Selector.open();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
while (!isClosed) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(buffer);
if (readBytes > 0) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
String body = new String(bytes, StandardCharsets.UTF_8);
System.out.println(body);
}
}
iterator.remove();
}
}
socketChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
Scanner sc = new Scanner(System.in);
while (true) {
String msg = sc.next();
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
buffer.put(msg.getBytes(StandardCharsets.UTF_8));
buffer.flip();
try {
socketChannel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if ("quit".equals(msg)) {
this.isClosed = true;
break;
}
}
}).start();
}
public static void main(String[] args) throws IOException {
new NIOClient().start();
}
}
[客戶端一控制檯]
我是lzc
/127.0.0.1:13003==>我是lisi
lisi你好啊
/127.0.0.1:13003==>你好你好
[客戶端二控制檯]
/127.0.0.1:12977==>我是lzc
我是lisi
/127.0.0.1:12977==>lisi你好啊
你好你好
本作品採用《CC 協議》,轉載必須註明作者和本文連結