Java NIO怎么实现聊天室程序
发表于:2025-01-17 作者:千家信息网编辑
千家信息网最后更新 2025年01月17日,本文小编为大家详细介绍"Java NIO怎么实现聊天室程序",内容详细,步骤清晰,细节处理妥当,希望这篇"Java NIO怎么实现聊天室程序"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来
千家信息网最后更新 2025年01月17日Java NIO怎么实现聊天室程序
本文小编为大家详细介绍"Java NIO怎么实现聊天室程序",内容详细,步骤清晰,细节处理妥当,希望这篇"Java NIO怎么实现聊天室程序"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
服务端:
package test.javanio; /** * @author * @version * CreateTime:2010-12-1 下午05:12:11 * Description: */ 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.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Date; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; public class MySocketServer implements Runnable { private boolean running; private Selector selector; String writeMsg; StringBuffer sb = new StringBuffer(); SelectionKey ssckey; public MySocketServer() { running = true; } public void init() { try { selector = Selector.open(); ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ssc.socket().bind(new InetSocketAddress(2345)); ssckey = ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("server is starting..." + new Date()); } catch (IOException ex) { Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { MySocketServer server = new MySocketServer(); new Thread(server).start(); } public void execute() { try { while (running) { int num = selector.select(); if (num > 0) { Iteratorit = selector.selectedKeys() .iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (!key.isValid()) continue; if (key.isAcceptable()) { System.out.println("isAcceptable"); getConn(key); } else if (key.isReadable()) { System.out.println("isReadable"); readMsg(key); } else if (key.isValid() && key.isWritable()) { if (writeMsg != null) { System.out.println("isWritable"); writeMsg(key); } } else break; } } Thread.yield(); } } catch (IOException ex) { Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE, null, ex); } } private void getConn(SelectionKey key) throws IOException { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); System.out.println("build connection :" + sc.socket().getRemoteSocketAddress()); } private void readMsg(SelectionKey key) throws IOException { sb.delete(0, sb.length()); SocketChannel sc = (SocketChannel) key.channel(); System.out.print(sc.socket().getRemoteSocketAddress() + " "); ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.clear(); int len = 0; StringBuffer sb = new StringBuffer(); while ((len = sc.read(buffer)) > 0) { buffer.flip(); sb.append(new String(buffer.array(), 0, len)); } if (sb.length() > 0) System.out.println("get from client:" + sb.toString()); if (sb.toString().trim().toLowerCase().equals("quit")) { sc.write(ByteBuffer.wrap("BYE".getBytes())); System.out.println("client is closed " + sc.socket().getRemoteSocketAddress()); key.cancel(); sc.close(); sc.socket().close(); } else { String toMsg = sc.socket().getRemoteSocketAddress() + "said:" + sb.toString(); System.out.println(toMsg); writeMsg = toMsg; /* * Iterator it=key.selector().keys().iterator(); * * while(it.hasNext()){ SelectionKey skey=it.next(); * if(skey!=key&&skey!=ssckey){ SocketChannel client=(SocketChannel) * skey.channel(); client.write(ByteBuffer.wrap(toMsg.getBytes())); * } * * } */ /* * * key.attach(toMsg); * key.interestOps(key.interestOps()|SelectionKey.OP_WRITE); */ Iterator it = key.selector().keys().iterator(); while (it.hasNext()) { SelectionKey skey = it.next(); if (skey != key && skey != ssckey) { if (skey.attachment() != null) { String str = (String) skey.attachment(); skey.attach(str + toMsg); } else { skey.attach(toMsg); } skey .interestOps(skey.interestOps() | SelectionKey.OP_WRITE); } } selector.wakeup();// 可有可无 } } public void run() { init(); execute(); } private void writeMsg(SelectionKey key) throws IOException { System.out.println("++++enter write+++"); SocketChannel sc = (SocketChannel) key.channel(); String str = (String) key.attachment(); sc.write(ByteBuffer.wrap(str.getBytes())); key.interestOps(SelectionKey.OP_READ); } }
客户端:
package test.javanio; /** * @author * @version * CreateTime:2010-12-1 下午05:12:46 * Description: */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.logging.Level; import java.util.logging.Logger; import java.util.Currency.*; public class MySocketClient implements Runnable { Selector selector; boolean running; SocketChannel sc; public MySocketClient() { running = true; } public void init() { try { sc = SocketChannel.open(); sc.configureBlocking(false); sc.connect(new InetSocketAddress("localhost", 2345)); } catch (IOException ex) { Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { MySocketClient client = new MySocketClient(); new Thread(client).start(); } public void execute() { int num = 0; try { while (!sc.finishConnect()) { } } catch (IOException ex) { Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE, null, ex); } ReadKeyBoard rkb = new ReadKeyBoard(); new Thread(rkb).start(); while (running) { try { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.clear(); StringBuffer sb = new StringBuffer(); Thread.sleep(500); while ((num = sc.read(buffer)) > 0) { sb.append(new String(buffer.array(), 0, num)); buffer.clear(); } if (sb.length() > 0) System.out.println(sb.toString()); if (sb.toString().toLowerCase().trim().equals("bye")) { System.out.println("closed...."); sc.close(); sc.socket().close(); rkb.close(); running = false; } } catch (InterruptedException ex) { Logger.getLogger(MySocketClient.class.getName()).log( Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MySocketClient.class.getName()).log( Level.SEVERE, null, ex); } } } public void run() { init(); execute(); } class ReadKeyBoard implements Runnable { boolean running2 = true; public ReadKeyBoard() { } public void close() { running2 = false; } public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); while (running2) { try { System.out.println("enter some commands:"); String str = reader.readLine(); sc.write(ByteBuffer.wrap(str.getBytes())); } catch (IOException ex) { Logger.getLogger(ReadKeyBoard.class.getName()).log( Level.SEVERE, null, ex); } } } } }
读到这里,这篇"Java NIO怎么实现聊天室程序"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。
程序
聊天室
文章
内容
妥当
可有可无
客户
客户端
思路
新知
更多
步骤
知识
知识点
篇文章
细节
行业
资讯
资讯频道
跟着
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
web 代理服务器
360网络安全学院题目
青岛博赛网络技术有限公司
阿里云服务器 如何使用
csgo不能建立本地服务器
广东网络技术转让平均价格
河北软件开发推广
江门嵌入式软件开发流程价格
服务器机房的分类
市委网络安全挂牌
dns服务器的ip
网络安全宣传网贷
腾讯的服务器为什么放在美国
计算机信息网络技术的课程设置
广东小明网络技术有限公司
软件开发宣传素材
电脑怎么创建代理服务器
软件开发费的合同模板
网易我的世界服务器给自己权限
我的世界基岩版看不到服务器名称
猎聘 软件开发工程师
迅雷科技深圳互联网
高通软件开发类笔试
江西中小学校园网络安全
sql数据库高级教程
获取到的数据写入数据库
数据库原理查看建的库
网络安全课程进校园的手抄报
怎么设置数据库的安全策略
嘉兴电商系统软件开发