利用SocketChannel ServerSocketChannel实现简单的聊天室
package com.mock;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class TestSocketChannel {
@Test
public void client() throws IOException {
//获取通道
SocketChannel client = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
//切换非阻塞模式
client.configureBlocking(false);
//获取缓冲
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//键盘输入
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String s = scanner.next();
byteBuffer.put(s.getBytes());
byteBuffer.flip();
//向服务端发送数据
client.write(byteBuffer);
byteBuffer.clear();
}
client.close();
}
@Test
public void server() throws IOException {
//获取通道
ServerSocketChannel server = ServerSocketChannel.open();
//切换非阻塞模式
server.configureBlocking(false);
server.bind(new InetSocketAddress(8080));
//获取选择器
Selector selector = Selector.open();
//注册接受事件
server.register(selector, SelectionKey.OP_ACCEPT);
//如果有准备就绪的事件
while (selector.select() > 0) {
//获取就绪事件
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
//如果是客户端连接事件
if (selectionKey.isAcceptable()) {
SocketChannel client = server.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
//如果是读事件
} else if (selectionKey.isReadable()) {
SocketChannel client = (SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int len = 0;
while ((len = client.read(byteBuffer)) > 0) {
byteBuffer.flip();
System.out.println("收到客户端数据: " + new String(byteBuffer.array(), 0, len));
byteBuffer.clear();
}
}
//一定要移除已经处理的事件,不然会一直循环重复处理就绪事件
iterator.remove();
}
}
}
}
来源:CSDN
作者:周莫客
链接:https://blog.csdn.net/MockZhou/article/details/103653873