Java基于NIO怎么实现聊天室功能,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Sever端
package com.qst.one; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.Channel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; import java.nio.ByteBuffer; public class Server { private static SocketChannel accept; public static void main(String[] args) { System.out.println("----服务端启动---"); try { // 获取通道 ServerSocketChannel channel = ServerSocketChannel.open(); // 配置非阻塞模式 channel.configureBlocking(false); // 绑定连接的端口 channel.bind(new InetSocketAddress(9999)); // 获取选择器 Selector selector = Selector.open(); // 注册通道到选择器上,开始监听事件 channel.register(selector, SelectionKey.OP_ACCEPT); // 使用选择器进行轮询 while (selector.select() > 0) { // 获取到选择器上所有注册的通道中已经就绪好的事件 Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { // 获取事件 SelectionKey next = iterator.next(); // 判断事件类型 if (next.isAcceptable()) { // 获取通道 accept = channel.accept(); // 获取当前连接分配地址 SocketAddress address = accept.getLocalAddress(); System.out.println(address + "上线了"); // 切换模式 accept.configureBlocking(false); // 将通道注册到选择器上 accept.register(selector, SelectionKey.OP_READ); } // 如果为读模式 else if (next.isReadable()) { SocketChannel accept = (SocketChannel) next.channel(); // 读取事件 ByteBuffer buffer = ByteBuffer.allocate(1024); int len; while ((len = accept.read(buffer)) > 0) { // 开启读模式 buffer.flip(); // System.out.println((char)len); System.out.println(new String(buffer.array(), 0, len)); // 归位 buffer.clear(); } } iterator.remove(); } } } catch (Exception e) { try { SocketAddress address = accept.getRemoteAddress(); System.out.println(address+"离线了"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }
Client端
package com.qst.one; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SocketChannel; import java.util.Scanner; import java.nio.ByteBuffer; public class Client { public static void main(String[] args) throws IOException { SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 9999)); channel.configureBlocking(false); ByteBuffer buffer = ByteBuffer.allocate(1024); Scanner sc = new Scanner(System.in); SocketAddress address = channel.getLocalAddress(); System.out.println(address+"ready~~~"); while(true) { System.out.print("tim:"); String name = sc.nextLine(); buffer.put(("tim :"+name).getBytes()); buffer.flip(); channel.write(buffer); buffer.clear(); } } }
看完上述内容,你们掌握Java基于NIO怎么实现聊天室功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。