java-chat-room 聊天室基于Nio

xiaoxiao2025-07-18  9

Client

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.nio.charset.Charset; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class ClientNio { private Selector selector = null; static final int port = 8082; private Charset charset = Charset.forName("UTF-8"); private SocketChannel sc = null; private String name = ""; private static String USER_EXIST = "system message: user exist, please change a name"; private static String USER_CONTENT_SPILIT = "#@#"; public void init() throws IOException { name = System.currentTimeMillis()+ ""; System.out.println("user name === " + name); selector = Selector.open(); //连接远程主机的IP和端口 sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", port)); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); //开辟一个新线程来读取从服务器端的数据 new Thread(new ClientThread()).start(); //在主线程中 从键盘读取数据输入到服务器端 Scanner scan = new Scanner(System.in); //注册 sc.write(charset.encode(name)); while (scan.hasNextLine()) { String line = scan.nextLine(); if ("".equals(line)) continue; //不允许发空消息 if ("".equals(name)) { name = line; line = name + USER_CONTENT_SPILIT; } else { line = name + USER_CONTENT_SPILIT + line; } sc.write(charset.encode(line));//sc既能写也能读,这边是写 } } private class ClientThread implements Runnable { public void run() { try { while (true) { int readyChannels = selector.select(); if (readyChannels == 0) continue; Set selectedKeys = selector.selectedKeys(); //可以通过这个方法,知道可用通道的集合 Iterator keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey sk = (SelectionKey) keyIterator.next(); keyIterator.remove(); dealWithSelectionKey(sk); } } } catch (IOException io) { } } private void dealWithSelectionKey(SelectionKey sk) throws IOException { if (sk.isReadable()) { //使用 NIO 读取 Channel中的数据,这个和全局变量sc是一样的,因为只注册了一个SocketChannel //sc既能写也能读,这边是读 SocketChannel sc = (SocketChannel) sk.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); String content = ""; while (sc.read(buff) > 0) { buff.flip(); content += charset.decode(buff); } //若系统发送通知名字已经存在,则需要换个昵称 if (USER_EXIST.equals(content)) { name = ""; } System.out.println(content); sk.interestOps(SelectionKey.OP_READ); } } } public static void main(String[] args) throws IOException { new ClientNio().init(); } }

Server

import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; public class ServerNio { private Selector selector = null; static final int port = 8082; private Charset charset = Charset.forName("UTF-8"); //用来记录在线人数,以及昵称 private static List<String> users = new ArrayList<String>(); private static String USER_EXIST = "system message: user exist, please change a name"; //相当于自定义协议格式,与客户端协商好 private static String USER_CONTENT_SPILIT = "#@#"; private static boolean flag = false; public void init() throws IOException { selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port)); //非阻塞的方式 server.configureBlocking(false); //注册到选择器上,设置为监听状态 server.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server is listening now..."); while (true) { int readyChannels = selector.select(); if (readyChannels == 0) continue; Set selectedKeys = selector.selectedKeys(); // 可以通过这个方法,知道可用通道的集合 Iterator keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey sk = (SelectionKey) keyIterator.next(); keyIterator.remove(); dealWithSelectionKey(server, sk); } } } public void dealWithSelectionKey(ServerSocketChannel server, SelectionKey sk) throws IOException { if (sk.isAcceptable()) { SocketChannel sc = server.accept(); //非阻塞模式 sc.configureBlocking(false); //注册选择器,并设置为读取模式,收到一个连接请求,然后起一个SocketChannel,并注册到selector上,之后这个连接的数据,就由这个SocketChannel处理 sc.register(selector, SelectionKey.OP_READ); //将此对应的channel设置为准备接受其他客户端请求 sk.interestOps(SelectionKey.OP_ACCEPT); // System.out.println("Server is listening from client :" + sc.getRemoteAddress()); sc.write(charset.encode("Please input your name.")); } //处理来自客户端的数据读取请求 if (sk.isReadable()) { //返回该SelectionKey对应的 Channel,其中有数据需要读取 SocketChannel sc = (SocketChannel) sk.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); StringBuilder content = new StringBuilder(); try { while (sc.read(buff) > 0) { buff.flip(); content.append(charset.decode(buff)); } // System.out.println("Server is listening from client " + sc.getRemoteAddress() + " data rev is: " + content); //将此对应的channel设置为准备下一次接受数据 sk.interestOps(SelectionKey.OP_READ); } catch (IOException io) { sk.cancel(); if (sk.channel() != null) { sk.channel().close(); } } if (content.length() > 0) { String[] arrayContent = content.toString().split(USER_CONTENT_SPILIT); //注册用户 if (arrayContent.length == 1) { String name = arrayContent[0]; users.add(name); int num = onlineNum(selector); String message = "welcome " + name + " to chat room! Online numbers:" + num; System.out.println(message); broadCast(selector, null, message); } //注册完了,发送消息 else if ( arrayContent.length > 1) { String name = arrayContent[0]; String message = content.substring(name.length() + USER_CONTENT_SPILIT.length()); message = arrayContent[1]; message = name + " say " + message; String message1 = "get message: " + message ; System.out.println(message1); if (users.contains(name)) { //不回发给发送此内容的客户端 broadCast(selector, sc, message); } } } } } //TODO 要是能检测下线,就不用这么统计了 public static int onlineNum(Selector selector) { int res = 0; for (SelectionKey key : selector.keys()) { Channel targetchannel = key.channel(); if (targetchannel instanceof SocketChannel) { res++; } } return res; } public void broadCast(Selector selector, SocketChannel except, String content) throws IOException { //广播数据到所有的SocketChannel中 for (SelectionKey key : selector.keys()) { Channel targetchannel = key.channel(); //如果except不为空,不回发给发送此内容的客户端 if (targetchannel instanceof SocketChannel && targetchannel != except) { SocketChannel dest = (SocketChannel) targetchannel; dest.write(charset.encode(content)); } } } public static void main(String[] args) throws IOException { new ServerNio().init(); } }

github源码:https://github.com/weiyang00/chat-rooms/tree/master/java-chat-room/src/main/java/example/nio

转载请注明原文地址: https://www.6miu.com/read-5033287.html

最新回复(0)