最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java?NIO實現(xiàn)多人聊天室

 更新時間:2021年11月24日 09:55:57   作者:RivenDong  
這篇文章主要為大家詳細介紹了Java?NIO實現(xiàn)多人聊天室,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了Java NIO實現(xiàn)多人聊天室的具體代碼,供大家參考,具體內(nèi)容如下

1. 服務(wù)器端代碼

ChatServer類:

package nio.test.server;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Set;

public class ChatServer {

    private static final int DEFAULT_PORT = 8888;
    private static final String QUIT = "quit";
    private static final int BUFFER = 1024;
    private ServerSocketChannel serverSocketChannel; //服務(wù)器端用于處理IO的通道
    private Selector selector;
    private ByteBuffer byteBufferReader = ByteBuffer.allocate(BUFFER); //用來讀取消息
    private ByteBuffer byteBufferWriter = ByteBuffer.allocate(BUFFER); //用來轉(zhuǎn)發(fā)消息時寫入其他通道的緩沖區(qū)
    private Charset charset = Charset.forName("UTF-8"); //標準化編碼解碼
    private int port;

    public ChatServer(){
        this(DEFAULT_PORT);
    }
    public ChatServer(int port){
        this.port = port;
    }
    private void start(){
        try {
            serverSocketChannel = ServerSocketChannel.open(); //創(chuàng)建服務(wù)器套接字通道
            serverSocketChannel.configureBlocking(false); //設(shè)置為非阻塞式調(diào)用
            serverSocketChannel.socket().bind(new InetSocketAddress(port));

            selector = Selector.open(); //打開選擇器
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("啟動服務(wù)器,監(jiān)聽端口:" + port + "...");

            while (true) {
                selector.select();
                //selectionKeys包含了select()接收到的所有事件
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                for(SelectionKey key : selectionKeys){
                    //處理被觸發(fā)的事件
                    handles(key);
                }
                selectionKeys.clear(); //把集合清空
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(selector);//啟到既關(guān)閉selector又關(guān)閉通道的作用
        }
    }

    /**
     * 處理被觸發(fā)的事件
     * @param key 每當通道被選擇器注冊時,都會創(chuàng)建一個選擇鍵
     * @throws IOException
     */
    private void handles(SelectionKey key) throws IOException {
        // 觸發(fā) ACCEPT事件 --- 和客戶端建立了連接
        if(key.isAcceptable()){
            ServerSocketChannel server = (ServerSocketChannel) key.channel();
            SocketChannel client = server.accept();
            client.configureBlocking(false);
            client.register(selector, SelectionKey.OP_READ);
            System.out.println(getClientName(client) + "已連接");
        }
        // 觸發(fā) READ事件 --- 客戶端發(fā)送了消息給服務(wù)器端
        else if(key.isReadable()){
            SocketChannel client = (SocketChannel) key.channel();
            String fwdMsg = receive(client); //讀取客戶端消息
            if(fwdMsg.isEmpty()){ //客戶端異常
                key.cancel(); //不再監(jiān)視這個通道上的read事件
                selector.wakeup();
            }else {
                forwardMessage(client, fwdMsg); //轉(zhuǎn)發(fā)客戶端消息

                // 檢查用戶是否退出
                if(readyToQuit(fwdMsg)){
                    key.cancel();//解除監(jiān)聽
                    selector.wakeup();
                    System.out.println(getClientName(client) + "已斷開");
                }
            }
        }
    }

    /**
     * 用于轉(zhuǎn)發(fā)消息
     * @param client
     * @param fwdMsg
     * @throws IOException
     */
    private void forwardMessage(SocketChannel client, String fwdMsg) throws IOException {
         for(SelectionKey key : selector.keys()){
             Channel connectedClient = key.channel();
             if(connectedClient instanceof ServerSocketChannel) continue;

             if(key.isValid() && !client.equals(connectedClient)) {
                 byteBufferWriter.clear();
                 byteBufferWriter.put(charset.encode((getClientName(client)) + ":" + fwdMsg));
                 byteBufferWriter.flip(); //寫轉(zhuǎn)讀
                 while(byteBufferWriter.hasRemaining()){
                     ((SocketChannel)connectedClient).write(byteBufferWriter);
                 }
             }
         }
    }
    private String receive(SocketChannel client) throws IOException {
        byteBufferReader.clear();
        while(client.read(byteBufferReader) > 0);
        byteBufferReader.flip();
        return String.valueOf(charset.decode(byteBufferReader));

    }
    private String getClientName(SocketChannel client){
        return "客戶端[" + client.socket().getPort() + "]";
    }
    private boolean readyToQuit(String msg){
        return QUIT.equals(msg);
    }
    private void close(Closeable closeable){
        if(closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ChatServer chatServer = new ChatServer(6666);
        chatServer.start();

    }
}

2. 客戶端代碼

ChatClient類:

package nio.test.client;


import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Set;

public class ChatClient {
    private static final String DEFAULT_SERVER_HOST = "127.0.0.1";
    private static final int DEFAULT_SERVER_PORT = 6666;
    private static final String QUIT = "quit";
    private static final int BUFFER = 1024;

    private String host;
    private int port;
    private SocketChannel client;
    private ByteBuffer byteBufferReader = ByteBuffer.allocate(BUFFER);
    private ByteBuffer byteBufferWriter = ByteBuffer.allocate(BUFFER);
    private Selector selector;
    private Charset charset = Charset.forName("UTF-8");

    public ChatClient(){
        this(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT);
    }
    public ChatClient(String host, int port){
        this.host = host;
        this.port = port;
    }
    public boolean readyToQuit(String msg){
        return QUIT.equals(msg);
    }
    private void close(Closeable closeable){
        if(closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void start(){
        try {
            client = SocketChannel.open();
            client.configureBlocking(false);

            selector = Selector.open();
            client.register(selector, SelectionKey.OP_CONNECT);
            client.connect(new InetSocketAddress(host, port));
            while(true){
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                for(SelectionKey key : selectionKeys){
                    handles(key);
                }
                selectionKeys.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClosedSelectorException e){
            //用戶正常退出
        }finally {
            close(selector);
        }
    }
    private void handles(SelectionKey key) throws IOException {
        // CONNECT事件 連接就緒事件
        if(key.isConnectable()){
            SocketChannel client = (SocketChannel)key.channel();
            if(client.isConnectionPending()){//連接處于就緒狀態(tài)
                client.finishConnect();
                // 處理用戶的輸入信息
                new Thread(new UserInputHandler(this)).start();
            }
            client.register(selector, SelectionKey.OP_READ);
        }
        // READ事件  服務(wù)器轉(zhuǎn)發(fā)消息
        else if(key.isReadable()){
            SocketChannel client = (SocketChannel)key.channel();
            String msg = receive(client);
            if(msg.isEmpty()){
                // 服務(wù)器出現(xiàn)異常
                close(selector);
            }else{
                System.out.println(msg);
            }
        }
    }
    public void send(String msg) throws IOException {
        if(msg.isEmpty()){
            return ;
        }else{
            byteBufferWriter.clear();
            byteBufferWriter.put(charset.encode(msg));
            byteBufferWriter.flip();
            while(byteBufferWriter.hasRemaining()){
                client.write(byteBufferWriter);
            }
            //檢查用戶是否準備退出
            if(readyToQuit(msg)){
                close(selector);
            }
        }
    }
    private String receive(SocketChannel client) throws IOException {
        byteBufferReader.clear();
        while(client.read(byteBufferReader) > 0);
        byteBufferReader.flip();
        return String.valueOf(charset.decode(byteBufferReader));
    }
    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        chatClient.start();
    }
}

UserInputHandler類:

package nio.test.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class UserInputHandler implements Runnable{

    private ChatClient chatclient;
    public UserInputHandler(ChatClient chatClient){
        this.chatclient = chatClient;
    }
    /**r
     *
     */
    @Override
    public void run() {
        try {
            //等待用戶輸入的消息
            BufferedReader consoleReader = new BufferedReader(
                    new InputStreamReader(System.in)
            );
            while(true){
                String input = consoleReader.readLine();
                //向服務(wù)器發(fā)送消息
                chatclient.send(input);
                //檢查用戶是否準備退出
                if(chatclient.readyToQuit(input)){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 執(zhí)行效果截圖

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java文件操作報錯:java.io.FileNotFoundException(拒絕訪問)問題

    java文件操作報錯:java.io.FileNotFoundException(拒絕訪問)問題

    在進行編程時,經(jīng)常會遇到因疏忽小細節(jié)而導(dǎo)致的錯誤,如忘記在路徑后添加文件名,本文通過一個具體的修改前后對比示例,解釋了錯誤原因,并給出了解決方案,這類經(jīng)驗分享對編程學(xué)習(xí)者具有參考價值
    2024-10-10
  • Java基礎(chǔ)之static的用法

    Java基礎(chǔ)之static的用法

    這篇文章主要介紹了Java基礎(chǔ)之static的用法,文中有非常詳細的代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有很大的幫助,需要的朋友可以參考下
    2021-05-05
  • java項目jar包與jdk的版本不兼容的問題解決

    java項目jar包與jdk的版本不兼容的問題解決

    這篇文章主要介紹了java項目jar包與jdk的版本不兼容的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10
  • 詳解使用Spring AOP和自定義注解進行參數(shù)檢查

    詳解使用Spring AOP和自定義注解進行參數(shù)檢查

    本篇文章主要介紹了詳解使用Spring AOP和自定義注解進行參數(shù)檢查,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • Maven Optional依賴屬性的含義及妙用

    Maven Optional依賴屬性的含義及妙用

    這篇文章主要為大家介紹了Maven Optional依賴屬性的含義及妙用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-05-05
  • Java之a(chǎn)pi網(wǎng)關(guān)斷言及過濾器案例講解

    Java之a(chǎn)pi網(wǎng)關(guān)斷言及過濾器案例講解

    這篇文章主要介紹了Java之a(chǎn)pi網(wǎng)關(guān)斷言及過濾器案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Java如何把文件夾打成壓縮包并導(dǎo)出

    Java如何把文件夾打成壓縮包并導(dǎo)出

    這篇文章主要介紹了Java如何把文件夾打成壓縮包并導(dǎo)出,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 微信公眾號開發(fā)之設(shè)置自定義菜單實例代碼【java版】

    微信公眾號開發(fā)之設(shè)置自定義菜單實例代碼【java版】

    這篇文章主要介紹了微信公眾號開發(fā)之設(shè)置自定義菜單實例代碼,本實例是為了實現(xiàn)在管理后臺實現(xiàn)微信菜單的添加刪除管理。需要的朋友可以參考下
    2018-06-06
  • 深入淺析Java反射機制

    深入淺析Java反射機制

    Java反射機制是在運行狀態(tài)中,對于任意一個類,都能夠知道這個類的所有屬性和方法;對于任意一個對象,都能夠調(diào)用它的任意一個方法和屬性;這種動態(tài)獲取的信息以及動態(tài)調(diào)用對象的方法的功能稱為Java語言的反射機制
    2015-11-11
  • spring boot 集成 swagger3及配置方法

    spring boot 集成 swagger3及配置方法

    Swagger 3是一種開源的API描述工具,它可以幫助開發(fā)人員設(shè)計、構(gòu)建、文檔化和測試API,這篇文章主要介紹了spring boot 集成 swagger3,需要的朋友可以參考下
    2023-05-05

最新評論

渭源县| 莱阳市| 偏关县| 阳春市| 锡林郭勒盟| 溧阳市| 全州县| 聂荣县| 阜宁县| 井冈山市| 阜新| 昔阳县| 广东省| 朝阳市| 资溪县| 乐平市| 漳平市| 当涂县| 津市市| 瑞金市| 旬阳县| 咸宁市| 东至县| 鄂温| 安康市| 周口市| 抚松县| 壶关县| 海口市| 辽阳县| 琼海市| 沧源| 渝中区| 出国| 湖北省| 泽普县| 东明县| 施秉县| 怀柔区| 阳泉市| 沧州市|