Java NIO 聊天室实例

开发 后端
最近写了个Java NIO聊天室聊天的程序,NIO学习起来比较困难的,我的代码能给大家起到一个抛砖引玉的作用!

最近写了个Java NIO聊天室聊天的程序,NIO学习起来比较困难的,我的代码能给大家起到一个抛砖引玉的作用!

服务端:

  1. package test.javanio;  
  2.  
  3. /**  
  4.  * @author   
  5.  * @version   
  6.  * CreateTime:2010-12-1 下午05:12:11  
  7.  * Description:  
  8.  */ 
  9. import java.io.IOException;  
  10. import java.net.InetSocketAddress;  
  11. import java.nio.ByteBuffer;  
  12. import java.nio.channels.SelectionKey;  
  13. import java.nio.channels.Selector;  
  14. import java.nio.channels.ServerSocketChannel;  
  15. import java.nio.channels.SocketChannel;  
  16. import java.util.Date;  
  17. import java.util.Iterator;  
  18. import java.util.logging.Level;  
  19. import java.util.logging.Logger;  
  20.  
  21. public class MySocketServer implements Runnable {  
  22.  
  23.     private boolean running;  
  24.  
  25.     private Selector selector;  
  26.     String writeMsg;  
  27.     StringBuffer sb = new StringBuffer();  
  28.     SelectionKey ssckey;  
  29.  
  30.     public MySocketServer() {  
  31.  
  32.         running = true;  
  33.  
  34.     }  
  35.  
  36.     public void init() {  
  37.         try {  
  38.             selector = Selector.open();  
  39.             ServerSocketChannel ssc = ServerSocketChannel.open();  
  40.             ssc.configureBlocking(false);  
  41.             ssc.socket().bind(new InetSocketAddress(2345));  
  42.             ssckey = ssc.register(selector, SelectionKey.OP_ACCEPT);  
  43.             System.out.println("server is starting..." + new Date());  
  44.         } catch (IOException ex) {  
  45.             Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,  
  46.                     null, ex);  
  47.         }  
  48.     }  
  49.  
  50.     public static void main(String[] args) {  
  51.         MySocketServer server = new MySocketServer();  
  52.         new Thread(server).start();  
  53.  
  54.     }  
  55.  
  56.     public void execute() {  
  57.         try {  
  58.             while (running) {  
  59.                 int num = selector.select();  
  60.                 if (num > 0) {  
  61.                     Iterator<SelectionKey> it = selector.selectedKeys()  
  62.                             .iterator();  
  63.                     while (it.hasNext()) {  
  64.                         SelectionKey key = it.next();  
  65.                         it.remove();  
  66.                         if (!key.isValid())  
  67.                             continue;  
  68.                         if (key.isAcceptable()) {  
  69.                             System.out.println("isAcceptable");  
  70.                             getConn(key);  
  71.                         } else if (key.isReadable()) {  
  72.                             System.out.println("isReadable");  
  73.                             readMsg(key);  
  74.                         }  
  75.  
  76.                         else if (key.isValid() && key.isWritable()) {  
  77.                             if (writeMsg != null) {  
  78.                                 System.out.println("isWritable");  
  79.                                 writeMsg(key);  
  80.                             }  
  81.  
  82.                         }  
  83.  
  84.                         else 
  85.                             break;  
  86.  
  87.                     }  
  88.  
  89.                 }  
  90.                 Thread.yield();  
  91.             }  
  92.  
  93.         } catch (IOException ex) {  
  94.             Logger.getLogger(MySocketServer.class.getName()).log(Level.SEVERE,  
  95.                     null, ex);  
  96.         }  
  97.     }  
  98.  
  99.     private void getConn(SelectionKey key) throws IOException {  
  100.         ServerSocketChannel ssc = (ServerSocketChannel) key.channel();  
  101.         SocketChannel sc = ssc.accept();  
  102.         sc.configureBlocking(false);  
  103.         sc.register(selector, SelectionKey.OP_READ);  
  104.         System.out.println("build connection :" 
  105.                 + sc.socket().getRemoteSocketAddress());  
  106.     }  
  107.  
  108.     private void readMsg(SelectionKey key) throws IOException {  
  109.         sb.delete(0, sb.length());  
  110.         SocketChannel sc = (SocketChannel) key.channel();  
  111.         System.out.print(sc.socket().getRemoteSocketAddress() + " ");  
  112.         ByteBuffer buffer = ByteBuffer.allocate(1024);  
  113.         buffer.clear();  
  114.         int len = 0;  
  115.         StringBuffer sb = new StringBuffer();  
  116.         while ((len = sc.read(buffer)) > 0) {  
  117.             buffer.flip();  
  118.             sb.append(new String(buffer.array(), 0, len));  
  119.         }  
  120.         if (sb.length() > 0)  
  121.             System.out.println("get from client:" + sb.toString());  
  122.         if (sb.toString().trim().toLowerCase().equals("quit")) {  
  123.             sc.write(ByteBuffer.wrap("BYE".getBytes()));  
  124.             System.out.println("client is closed " 
  125.                     + sc.socket().getRemoteSocketAddress());  
  126.             key.cancel();  
  127.             sc.close();  
  128.             sc.socket().close();  
  129.  
  130.         } else {  
  131.             String toMsg = sc.socket().getRemoteSocketAddress() + "said:" 
  132.                     + sb.toString();  
  133.             System.out.println(toMsg);  
  134.  
  135.             writeMsg = toMsg;  
  136.  
  137.             /*  
  138.              * Iterator<SelectionKey> it=key.selector().keys().iterator();  
  139.              *   
  140.              * while(it.hasNext()){ SelectionKey skey=it.next();  
  141.              * if(skey!=key&&skey!=ssckey){ SocketChannel client=(SocketChannel)  
  142.              * skey.channel(); client.write(ByteBuffer.wrap(toMsg.getBytes()));  
  143.              * }  
  144.              *   
  145.              * }  
  146.              */ 
  147.  
  148.             /*  
  149.              *   
  150.              * key.attach(toMsg);  
  151.              * key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);  
  152.              */ 
  153.             Iterator<SelectionKey> it = key.selector().keys().iterator();  
  154.  
  155.             while (it.hasNext()) {  
  156.                 SelectionKey skey = it.next();  
  157.                 if (skey != key && skey != ssckey) {  
  158.                     if (skey.attachment() != null) {  
  159.                         String str = (String) skey.attachment();  
  160.                         skey.attach(str + toMsg);  
  161.                     } else {  
  162.                         skey.attach(toMsg);  
  163.                     }  
  164.                     skey  
  165.                             .interestOps(skey.interestOps()  
  166.                                     | SelectionKey.OP_WRITE);  
  167.                 }  
  168.  
  169.             }  
  170.             selector.wakeup();// 可有可无  
  171.  
  172.         }  
  173.  
  174.     }  
  175.  
  176.     public void run() {  
  177.         init();  
  178.         execute();  
  179.     }  
  180.  
  181.     private void writeMsg(SelectionKey key) throws IOException {  
  182.  
  183.         System.out.println("++++enter write+++");  
  184.         SocketChannel sc = (SocketChannel) key.channel();  
  185.         String str = (String) key.attachment();  
  186.  
  187.         sc.write(ByteBuffer.wrap(str.getBytes()));  
  188.         key.interestOps(SelectionKey.OP_READ);  
  189.     }  

客户端:

  1. package test.javanio;  
  2.  
  3. /**  
  4.  * @author   
  5.  * @version   
  6.  * CreateTime:2010-12-1 下午05:12:46  
  7.  * Description:  
  8.  */ 
  9. import java.io.BufferedReader;  
  10. import java.io.IOException;  
  11. import java.io.InputStreamReader;  
  12. import java.net.InetSocketAddress;  
  13. import java.nio.ByteBuffer;  
  14. import java.nio.channels.Selector;  
  15. import java.nio.channels.SocketChannel;  
  16. import java.util.logging.Level;  
  17. import java.util.logging.Logger;  
  18. import java.util.Currency.*;  
  19.  
  20. public class MySocketClient implements Runnable {  
  21.     Selector selector;  
  22.  
  23.     boolean running;  
  24.  
  25.     SocketChannel sc;  
  26.  
  27.     public MySocketClient() {  
  28.         running = true;  
  29.  
  30.     }  
  31.  
  32.     public void init() {  
  33.         try {  
  34.             sc = SocketChannel.open();  
  35.             sc.configureBlocking(false);  
  36.             sc.connect(new InetSocketAddress("localhost"2345));  
  37.  
  38.         } catch (IOException ex) {  
  39.             Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,  
  40.                     null, ex);  
  41.         }  
  42.     }  
  43.  
  44.     public static void main(String[] args) {  
  45.  
  46.         MySocketClient client = new MySocketClient();  
  47.         new Thread(client).start();  
  48.     }  
  49.  
  50.     public void execute() {  
  51.  
  52.         int num = 0;  
  53.         try {  
  54.             while (!sc.finishConnect()) {  
  55.             }  
  56.         } catch (IOException ex) {  
  57.             Logger.getLogger(MySocketClient.class.getName()).log(Level.SEVERE,  
  58.                     null, ex);  
  59.         }  
  60.  
  61.         ReadKeyBoard rkb = new ReadKeyBoard();  
  62.         new Thread(rkb).start();  
  63.         while (running) {  
  64.             try {  
  65.  
  66.                 ByteBuffer buffer = ByteBuffer.allocate(1024);  
  67.                 buffer.clear();  
  68.  
  69.                 StringBuffer sb = new StringBuffer();  
  70.                 Thread.sleep(500);  
  71.  
  72.                 while ((num = sc.read(buffer)) > 0) {  
  73.                     sb.append(new String(buffer.array(), 0, num));  
  74.                     buffer.clear();  
  75.                 }  
  76.                 if (sb.length() > 0)  
  77.                     System.out.println(sb.toString());  
  78.                 if (sb.toString().toLowerCase().trim().equals("bye")) {  
  79.                     System.out.println("closed....");  
  80.  
  81.                     sc.close();  
  82.                     sc.socket().close();  
  83.                     rkb.close();  
  84.                     running = false;  
  85.                 }  
  86.             } catch (InterruptedException ex) {  
  87.                 Logger.getLogger(MySocketClient.class.getName()).log(  
  88.                         Level.SEVERE, null, ex);  
  89.             } catch (IOException ex) {  
  90.                 Logger.getLogger(MySocketClient.class.getName()).log(  
  91.                         Level.SEVERE, null, ex);  
  92.             }  
  93.         }  
  94.  
  95.     }  
  96.  
  97.     public void run() {  
  98.         init();  
  99.         execute();  
  100.     }  
  101.  
  102.     class ReadKeyBoard implements Runnable {  
  103.  
  104.         boolean running2 = true;  
  105.  
  106.         public ReadKeyBoard() {  
  107.  
  108.         }  
  109.  
  110.         public void close() {  
  111.             running2 = false;  
  112.         }  
  113.  
  114.         public void run() {  
  115.             BufferedReader reader = new BufferedReader(new InputStreamReader(  
  116.                     System.in));  
  117.             while (running2) {  
  118.                 try {  
  119.                     System.out.println("enter some commands:");  
  120.                     String str = reader.readLine();  
  121.                     sc.write(ByteBuffer.wrap(str.getBytes()));  
  122.  
  123.                 } catch (IOException ex) {  
  124.                     Logger.getLogger(ReadKeyBoard.class.getName()).log(  
  125.                             Level.SEVERE, null, ex);  
  126.                 }  
  127.             }  
  128.  
  129.         }  
  130.  
  131.     }  

原文链接:http://gcguchao8888-sina-com.iteye.com/blog/839021

【编辑推荐】

  1. 多线程NIO客户端实例
  2. 用nio实现Echo服务
  3. Java NIO 深入研究
  4. Java NIO聊天窗口实例
  5. Java NIO 经典实例代码
责任编辑:林师授 来源: 谷超的博客
相关推荐

2023-02-10 08:16:48

WebSocket简易聊天室

2022-07-26 14:53:10

WebSocket网络通信协议

2011-12-15 10:19:55

JavaNIO

2015-07-06 10:42:18

PHP聊天室应用

2021-11-16 09:38:10

鸿蒙HarmonyOS应用

2024-10-07 10:45:12

2023-01-13 00:02:41

2023-01-05 09:17:58

2022-11-14 08:01:48

2022-12-01 08:25:23

eTsTCP聊天室

2011-06-09 15:44:29

Spring

2011-12-15 11:19:08

JavaNIO

2015-08-06 17:17:33

swoole聊天室

2021-10-14 18:46:29

Websocket浏览器API

2022-04-18 10:36:48

社交软件聊天平台rocket.cha

2021-02-06 23:26:25

聊天室开发WebSocket

2024-01-18 11:15:46

Pythonsocket聊天室

2021-12-09 16:48:25

鸿蒙HarmonyOS应用

2011-12-07 14:41:51

JavaNIO
点赞
收藏

51CTO技术栈公众号