企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ package com.youge.nio.chat.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020/11/26 15:31 */ public class GroupChatServer { //定义属性 private static final int PORT = 6667; private Selector selector; private ServerSocketChannel listenChannel; //构造器,初始化工作 public GroupChatServer() { try { //创建选择器 selector = Selector.open(); //serverSocketChannel listenChannel = ServerSocketChannel.open(); //绑定端口 listenChannel.socket().bind(new InetSocketAddress(PORT)); //设置非阻塞模式 listenChannel.configureBlocking(false); //将listenChannel注册到selector,设定注册事件 listenChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { e.printStackTrace(); } } //监听 public void listen() { //循环处理 while (true) { try { int count = selector.select(2000); if (count > 0) {//有事件要处理 //遍历得到selectionKey集合 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { //取出selectionkey SelectionKey key = iterator.next(); //监听到accept事件 if (key.isAcceptable()) { SocketChannel socketChannel = listenChannel.accept(); //设置非阻塞 socketChannel.configureBlocking(false); //将连接过来的客户端注册到selector上 socketChannel.register(selector, SelectionKey.OP_READ); //提示 上线 System.out.println(socketChannel.getRemoteAddress() + "上线了."); } else if (key.isReadable()) {//读事件 //调用专门的读方法 readDate(key); } //将当前的selectionKey删除,防止重复操作 iterator.remove(); } } else { System.out.println("等待中...."); } } catch (IOException e) { e.printStackTrace(); } } } /** * 读取客户端消息 * * @param key */ private void readDate(SelectionKey key) { //定义一个SocketChannel SocketChannel channel = null; //获取channel channel = (SocketChannel) key.channel(); //创建byteBuffer ByteBuffer buffer = ByteBuffer.allocate(1023); //读取数据,把数据放入btyeBuffer try { int count = channel.read(buffer); if (count > 0) {//有数据 //把缓冲区的数据转为字符串 String message = new String(buffer.array()); //输出消息 System.out.println("from 客户端:" + message); //向其它客户端口转消息(去掉自己),专门写一个方法来处理 sendInfoToOtherClients(message,channel); } } catch (IOException e) { try { System.out.println(channel.getRemoteAddress()+"离线了"); //取消注册 key.cancel(); //关闭通道 channel.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } /** * 转发消息给其它客户端 * * @param msg * @param self */ public void sendInfoToOtherClients(String msg, SocketChannel self) { System.out.println("服务器转发消息中..."); //遍历所有注册到selector上的socketChannel,并排除 self for (SelectionKey key : selector.keys()) { //通过key取出对应的socketchannel // SocketChannel targetChannel = (SocketChannel) key.channel(); Channel targetChannel = key.channel(); //排除自己 if (targetChannel instanceof SocketChannel && targetChannel != self) { SocketChannel dest = (SocketChannel) targetChannel; //将msg存储到byteBuffer ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); try { dest.write(buffer); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { //创建服务器对象 GroupChatServer server = new GroupChatServer(); //启动监听 server.listen(); } } ~~~