NIO群聊(纯代码)

    科技2022-07-15  122

    客户端 package com.darwin.netty.nio.groupchat; 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.SocketChannel; import java.util.Iterator; import java.util.Scanner; /** * 群聊客户端 * * @author yanghang */ public class GroupChatClient { private Selector selector; private SocketChannel socketChannel; private final static int SERVER_PORT = 6667; private final static String SERVER_ADDRESS = "127.0.0.1"; private String userName; // 初始化 public GroupChatClient () throws IOException { selector = Selector.open(); // 连接服务端 socketChannel = SocketChannel.open(new InetSocketAddress(SERVER_ADDRESS, SERVER_PORT)); // 设置非阻塞 socketChannel.configureBlocking(false); // 将Channel设置到selector上 socketChannel.register(selector, SelectionKey.OP_READ); // 获取userName userName = socketChannel.getLocalAddress().toString().substring(1); System.out.println(userName + " is Ok"); } // 向服务器发送信息 public void sendInfo (String info) { info = userName + " : " + info; try { socketChannel.write(ByteBuffer.wrap(info.getBytes())); } catch (IOException e) { e.printStackTrace(); } } // 读取从服务器返回的消息 public void readInfo () { try { int readChannels = selector.select(); if(readChannels > 0) {//有可以用的通道 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if(key.isReadable()) { //得到相关的通道 SocketChannel sc = (SocketChannel) key.channel(); //得到一个Buffer ByteBuffer buffer = ByteBuffer.allocate(1024); //读取 sc.read(buffer); //把读到的缓冲区的数据转成字符串 String msg = new String(buffer.array()); System.out.println(msg.trim()); } } //删除当前的selectionKey, 防止重复操作 iterator.remove(); } }catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { // 启动客户端,不断的读取信息 GroupChatClient client = new GroupChatClient(); new Thread(() -> { for (; ; ) { client.readInfo(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); //发送数据给服务器端 Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String s = scanner.nextLine(); client.sendInfo(s); } } } 服务端 package com.darwin.netty.nio.groupchat; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Set; /** * 群聊服务端 * * @author yanghang */ public class GroupChatServer { private Selector selector; private ServerSocketChannel serverSocketChannel; private final static int PORT = 6667; public GroupChatServer() { try { selector = Selector.open(); serverSocketChannel = ServerSocketChannel.open(); // 绑定端口 serverSocketChannel.socket().bind(new InetSocketAddress(PORT)); // 设置非阻塞 serverSocketChannel.configureBlocking(false); // 将serverSocketChannel注册到selector serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (Exception ex) { ex.printStackTrace(); } } public void listen() { try { // 监听 for (; ; ) { int select = selector.select(); if (select > 0) { // 有事件要处理 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { // 有新的客户端连接 SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); // 将SocketChannel注册到selector上面 socketChannel.register(selector, SelectionKey.OP_READ); System.out.println(socketChannel.getRemoteAddress() + " 上线"); } if (key.isReadable()) { readData(key); } iterator.remove(); } } } } catch (Exception e) { e.printStackTrace(); } } private void readData(SelectionKey key) { // 获取关联的Channel SocketChannel socketChannel = null; try { socketChannel = (SocketChannel)key.channel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); int read = socketChannel.read(byteBuffer); if (read > 0) { // 把缓冲区的转换为字符串 String msg = new String(byteBuffer.array()); System.out.println("from 客户端: " + msg); // 向其他的客户端发送消息 sendOtherClient(msg, socketChannel); } } catch (IOException ex) { try { System.out.println(socketChannel.getRemoteAddress() + " 离线了.."); //取消注册 key.cancel(); //关闭通道 socketChannel.close(); }catch (IOException e2) { e2.printStackTrace();; } } } private void sendOtherClient(String msg, SocketChannel socketChannel) throws IOException { Set<SelectionKey> keys = selector.keys(); for (SelectionKey key:keys) { SelectableChannel selectableChannel = key.channel(); if (selectableChannel instanceof SocketChannel && selectableChannel != socketChannel) { SocketChannel channel = (SocketChannel)selectableChannel; // 发送信息 channel.write(ByteBuffer.wrap(msg.getBytes())); } } } public static void main(String[] args) { // 创建服务端处理器 GroupChatServer server = new GroupChatServer(); server.listen(); } }
    Processed: 0.014, SQL: 8