Java基于NIO实现聊天室功能
程序员文章站
2022-06-15 18:10:22
本文实例为大家分享了java基于nio实现聊天室功能的具体代码,供大家参考,具体内容如下sever端package com.qst.one;import java.io.ioexception;imp...
本文实例为大家分享了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(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。