氟塑料離心泵www.buybeng.com

          jquery教程http://www.software8.co/wzjs/jquery/

          java nio SocketChannel 服務器端與多客戶端 信息交互(聊天功能)

          服務器端: 
          Java代碼 : 
          1. import java.io.IOException;  
          2. import java.net.InetSocketAddress;  
          3. import java.net.ServerSocket;  
          4. import java.net.Socket;  
          5. import java.nio.ByteBuffer;  
          6. import java.nio.channels.SelectionKey;  
          7. import java.nio.channels.Selector;  
          8. import java.nio.channels.ServerSocketChannel;  
          9. import java.nio.channels.SocketChannel;  
          10. import java.nio.charset.Charset;  
          11. import java.util.HashMap;  
          12. import java.util.Map;  
          13. import java.util.Set;  
          14.   
          15. public class NIOSServer {  
          16.     private int port = 8888;  
          17.     //解碼buffer  
          18.     private Charset cs = Charset.forName("gbk");  
          19.     /*接受數據緩沖區*/  
          20.     private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);  
          21.     /*發送數據緩沖區*/  
          22.     private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);  
          23.     /*映射客戶端channel */  
          24.     private Map<String, SocketChannel> clientsMap = new HashMap<String, SocketChannel>();  
          25.     private static Selector selector;  
          26.       
          27.     public NIOSServer(int port){  
          28.         this.port = port;  
          29.         try {  
          30.             init();  
          31.         } catch (Exception e) {  
          32.             e.printStackTrace();  
          33.         }  
          34.     }  
          35.     private void init() throws IOException{  
          36.         /* 
          37.          *啟動服務器端,配置為非阻塞,綁定端口,注冊accept事件 
          38.          *ACCEPT事件:當服務端收到客戶端連接請求時,觸發該事件 
          39.          */  
          40.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
          41.         serverSocketChannel.configureBlocking(false);  
          42.         ServerSocket serverSocket = serverSocketChannel.socket();  
          43.         serverSocket.bind(new InetSocketAddress(port));  
          44.         selector = Selector.open();  
          45.         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  
          46.         System.out.println("server start on port:"+port);  
          47.     }  
          48.     /** 
          49.      * 服務器端輪詢監聽,select方法會一直阻塞直到有相關事件發生或超時 
          50.      */  
          51.     private void listen(){  
          52.         while (true) {  
          53.             try {  
          54.                 selector.select();//返回值為本次觸發的事件數  
          55.                 Set<SelectionKey> selectionKeys = selector.selectedKeys();  
          56.                 for(SelectionKey key : selectionKeys){  
          57.                     handle(key);  
          58.                 }  
          59.                 selectionKeys.clear();//清除處理過的事件  
          60.             } catch (Exception e) {  
          61.                 e.printStackTrace();  
          62.                 break;  
          63.             }  
          64.               
          65.         }  
          66.     }  
          67.     /** 
          68.      * 處理不同的事件 
          69.     */  
          70.     private void handle(SelectionKey selectionKey) throws IOException {  
          71.         ServerSocketChannel server = null;  
          72.         SocketChannel client = null;  
          73.         String receiveText=null;  
          74.         int count=0;  
          75.         if (selectionKey.isAcceptable()) {  
          76.             /* 
          77.              * 客戶端請求連接事件 
          78.              * serversocket為該客戶端建立socket連接,將此socket注冊READ事件,監聽客戶端輸入 
          79.              * READ事件:當客戶端發來數據,并已被服務器控制線程正確讀取時,觸發該事件 
          80.              */  
          81.             server = (ServerSocketChannel) selectionKey.channel();  
          82.             client = server.accept();  
          83.             client.configureBlocking(false);  
          84.             client.register(selector, SelectionKey.OP_READ);  
          85.         } else if (selectionKey.isReadable()) {  
          86.             /* 
          87.              * READ事件,收到客戶端發送數據,讀取數據后繼續注冊監聽客戶端 
          88.              */  
          89.             client = (SocketChannel) selectionKey.channel();  
          90.             rBuffer.clear();  
          91.             count = client.read(rBuffer);  
          92.             if (count > 0) {  
          93.                 rBuffer.flip();  
          94.                 receiveText = String.valueOf(cs.decode(rBuffer).array());  
          95.                 System.out.println(client.toString()+":"+receiveText);  
          96.                 dispatch(client, receiveText);  
          97.                 client = (SocketChannel) selectionKey.channel();  
          98.                 client.register(selector, SelectionKey.OP_READ);  
          99.             }  
          100.         }   
          101.     }  
          102.       
          103.     /** 
          104.      * 把當前客戶端信息 推送到其他客戶端 
          105.      */  
          106.     private void dispatch(SocketChannel client,String info) throws IOException{  
          107.         Socket s = client.socket();  
          108.         String name = "["+s.getInetAddress().toString().substring(1)+":"+Integer.toHexString(client.hashCode())+"]";  
          109.         if(!clientsMap.isEmpty()){  
          110.             for(Map.Entry<String, SocketChannel> entry : clientsMap.entrySet()){  
          111.                 SocketChannel temp = entry.getValue();  
          112.                 if(!client.equals(temp)){  
          113.                     sBuffer.clear();  
          114.                     sBuffer.put((name+":"+info).getBytes());  
          115.                     sBuffer.flip();  
          116.                     //輸出到通道  
          117.                     temp.write(sBuffer);  
          118.                 }  
          119.             }  
          120.         }  
          121.         clientsMap.put(name, client);  
          122.     }  
          123.     public static void main(String[] args) throws IOException {  
          124.         NIOSServer server = new NIOSServer(7777);  
          125.         server.listen();  
          126.     }  
          127. }  
          客戶端,可運行啟動多個: 
          Java代碼:  
          1. import java.io.BufferedReader;  
          2. import java.io.IOException;  
          3. import java.io.InputStreamReader;  
          4. import java.net.InetSocketAddress;  
          5. import java.nio.ByteBuffer;  
          6. import java.nio.channels.SelectionKey;  
          7. import java.nio.channels.Selector;  
          8. import java.nio.channels.SocketChannel;  
          9. import java.util.Date;  
          10. import java.util.Set;  
          11.   
          12. public class NIOClient {  
          13.     /*發送數據緩沖區*/  
          14.     private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);  
          15.     /*接受數據緩沖區*/  
          16.     private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);  
          17.     /*服務器端地址*/  
          18.     private InetSocketAddress SERVER;  
          19.     private static Selector selector;  
          20.     private static SocketChannel client;  
          21.     private static String receiveText;  
          22.     private static String sendText;  
          23.     private static int count=0;  
          24.       
          25.     public NIOClient(int port){  
          26.         SERVER = new InetSocketAddress("localhost", port);  
          27.         init();  
          28.     }  
          29.     public void init(){  
          30.         try {  
          31.            /* 
          32.              * 客戶端向服務器端發起建立連接請求 
          33.              */  
          34.             SocketChannel socketChannel = SocketChannel.open();  
          35.             socketChannel.configureBlocking(false);  
          36.             selector = Selector.open();  
          37.             socketChannel.register(selector, SelectionKey.OP_CONNECT);  
          38.             socketChannel.connect(SERVER);  
          39.             /* 
          40.              * 輪詢監聽客戶端上注冊事件的發生 
          41.              */  
          42.             while (true) {  
          43.                 selector.select();  
          44.                 Set<SelectionKey> keySet = selector.selectedKeys();  
          45.                 for(final SelectionKey key : keySet){  
          46.                     handle(key);  
          47.                 };  
          48.                 keySet.clear();  
          49.             }  
          50.         } catch (Exception e) {  
          51.             e.printStackTrace();  
          52.         }  
          53.     }  
          54.     public static void main(String[] args) throws IOException {  
          55.         NIOClient client = new NIOClient(7777);  
          56.     }  
          57.       
          58.     private void handle(SelectionKey selectionKey) throws IOException{  
          59.         if (selectionKey.isConnectable()) {  
          60.             /* 
          61.              * 連接建立事件,已成功連接至服務器 
          62.              */  
          63.             client = (SocketChannel) selectionKey.channel();  
          64.             if (client.isConnectionPending()) {  
          65.                 client.finishConnect();  
          66.                 System.out.println("connect success !");  
          67.                 sBuffer.clear();  
          68.                 sBuffer.put((new Date().toLocaleString()+" connected!").getBytes());  
          69.                 sBuffer.flip();  
          70.                 client.write(sBuffer);//發送信息至服務器  
          71.                 /* 原文來自站長網
          72.                  * 啟動線程一直監聽客戶端輸入,有信心輸入則發往服務器端 
          73.                  * 因為輸入流是阻塞的,所以單獨線程監聽 
          74.                  */  
          75.                 new Thread(){  
          76.                     @Override  
          77.                     public void run() {  
          78.                         while(true){  
          79.                             try {  
          80.                                 sBuffer.clear();  
          81.                                 InputStreamReader input = new InputStreamReader(System.in);  
          82.                                 BufferedReader br = new BufferedReader(input);  
          83.                                 sendText = br.readLine();  
          84.                                 /* 
          85.                                  * 未注冊WRITE事件,因為大部分時間channel都是可以寫的 
          86.                                  */  
          87.                                 sBuffer.put(sendText.getBytes());  
          88.                                 sBuffer.flip();  
          89.                                 client.write(sBuffer);  
          90.                             } catch (IOException e) {  
          91.                                 e.printStackTrace();  
          92.                                 break;  
          93.                             }  
          94.                       }  
          95.                     };  
          96.                 }.start();  
          97.             }  
          98.             //注冊讀事件  
          99.             client.register(selector, SelectionKey.OP_READ);  
          100.         } else if (selectionKey.isReadable()) {  
          101.             /* 
          102.              * 讀事件觸發 
          103.              * 有從服務器端發送過來的信息,讀取輸出到屏幕上后,繼續注冊讀事件 
          104.              * 監聽服務器端發送信息 
          105.              */  
          106.             client = (SocketChannel) selectionKey.channel();  
          107.             rBuffer.clear();  
          108.             count=client.read(rBuffer);  
          109.             if(count>0){  
          110.                 receiveText = new String( rBuffer.array(),0,count);  
          111.                 System.out.println(receiveText);  
          112.                 client = (SocketChannel) selectionKey.channel();  
          113.                 client.register(selector, SelectionKey.OP_READ);  
          114.             }  
          115.         }   
          116.     }  
          117. }  原文來自java教程網 http://www.software8.co/wzjs/java/   歡迎java愛好者前來投稿

          posted on 2013-01-05 15:51 你爸是李剛 閱讀(9132) 評論(3)  編輯  收藏

          評論

          # re: java nio SocketChannel 服務器端與多客戶端 信息交互(聊天功能) 2016-01-20 22:48 Irving

          selector.keys()應該是selector.selectedKeys()吧  回復  更多評論   

          # re: java nio SocketChannel 服務器端與多客戶端 信息交互(聊天功能) 2016-01-20 22:50 Irving

          看錯了sorry  回復  更多評論   

          # re: java nio SocketChannel 服務器端與多客戶端 信息交互(聊天功能) 2016-01-21 11:39 佛擋殺佛

          gdsgsg  回復  更多評論   


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2013年1月>
          303112345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          文章檔案

          技術網站

          行業網站

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          站長網 氟塑料離心泵 注塑機 液晶廣告機
          主站蜘蛛池模板: 柯坪县| 石景山区| 瑞昌市| 衢州市| 南和县| 旬阳县| 龙山县| 吴忠市| 专栏| 永和县| 临江市| 沙洋县| 郸城县| 吉首市| 台前县| 马鞍山市| 肇源县| 霍林郭勒市| 遵义市| 荥阳市| 十堰市| 铁岭市| 台江县| 成武县| 微博| 济宁市| 永济市| 义马市| 普安县| 丰镇市| 胶南市| 新兴县| 九江县| 龙川县| 弥勒县| 沁水县| 洮南市| 本溪市| 永清县| 泽普县| 石楼县|