溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Java?NIO如何實(shí)現(xiàn)群聊系統(tǒng)

發(fā)布時(shí)間:2021-11-23 21:05:44 來(lái)源:億速云 閱讀:165 作者:柒染 欄目:開(kāi)發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)Java NIO如何實(shí)現(xiàn)群聊系統(tǒng),文章內(nèi)容豐富且以專(zhuān)業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

實(shí)例要求:

1)編寫(xiě)一個(gè) NIO 群聊系統(tǒng),實(shí)現(xiàn)服務(wù)器端和客戶(hù)端之間的數(shù)據(jù)簡(jiǎn)單通訊(非阻塞)
2)實(shí)現(xiàn)多人群聊
3)服務(wù)器端:可以監(jiān)測(cè)用戶(hù)上線,離線,并實(shí)現(xiàn)消息轉(zhuǎn)發(fā)功能
4)客戶(hù)端:通過(guò)channel 可以無(wú)阻塞發(fā)送消息給其它所有用戶(hù),同時(shí)可以接受其它用戶(hù)發(fā)送的消息(有服務(wù)器轉(zhuǎn)發(fā)得到)
5)目的:進(jìn)一步理解NIO非阻塞網(wǎng)絡(luò)編程機(jī)制

服務(wù)端代碼:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
 
public class GroupChatServer {
    //定義屬性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;
 
    //構(gòu)造器
    //初始化工作
    public GroupChatServer() {
 
        try {
            //得到選擇器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel =  ServerSocketChannel.open();
            //綁定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //設(shè)置非阻塞模式
            listenChannel.configureBlocking(false);
            //將該listenChannel 注冊(cè)到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
 
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    //監(jiān)聽(tīng)
    public void listen() {
 
        System.out.println("監(jiān)聽(tīng)線程: " + Thread.currentThread().getName());
        try {
 
            //循環(huán)處理
            while (true) {
 
                int count = selector.select();
                if(count > 0) {//有事件處理
 
                    //遍歷得到selectionKey 集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        //取出selectionkey
                        SelectionKey key = iterator.next();
 
                        //監(jiān)聽(tīng)到accept
                        if(key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //將該 sc 注冊(cè)到seletor
                            sc.register(selector, SelectionKey.OP_READ);
                            //提示
                            System.out.println(sc.getRemoteAddress() + " 上線 ");
                        }
                        if(key.isReadable()) { //通道發(fā)送read事件,即通道是可讀的狀態(tài)
                            //處理讀 (專(zhuān)門(mén)寫(xiě)方法..)
                            readData(key);
                        }
                        //當(dāng)前的key 刪除,防止重復(fù)處理
                        iterator.remove();
                    }
 
                } else {
                    System.out.println("等待....");
                }
            }
 
        }catch (Exception e) {
            e.printStackTrace();
 
        }finally {
            //發(fā)生異常處理....
        }
    }
 
    //讀取客戶(hù)端消息
    private void readData(SelectionKey key) {
 
        //取到關(guān)聯(lián)的channle
        SocketChannel channel = null;
 
        try {
           //得到channel
            channel = (SocketChannel) key.channel();
            //創(chuàng)建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
 
            int count = channel.read(buffer);
            //根據(jù)count的值做處理
            if(count > 0) {
                //把緩存區(qū)的數(shù)據(jù)轉(zhuǎn)成字符串
                String msg = new String(buffer.array());
                //輸出該消息
                System.out.println("form 客戶(hù)端: " + msg);
                //向其它的客戶(hù)端轉(zhuǎn)發(fā)消息(去掉自己), 專(zhuān)門(mén)寫(xiě)一個(gè)方法來(lái)處理
                sendInfoToOtherClients(msg, channel);
            }
 
        }catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 離線了..");
                //取消注冊(cè)
                key.cancel();
                //關(guān)閉通道
                channel.close();
            }catch (IOException e2) {
                e2.printStackTrace();;
            }
        }
    }
 
    //轉(zhuǎn)發(fā)消息給其它客戶(hù)(通道)
    private void sendInfoToOtherClients(String msg, SocketChannel self ) throws  IOException{
 
        System.out.println("服務(wù)器轉(zhuǎn)發(fā)消息中...");
        System.out.println("服務(wù)器轉(zhuǎn)發(fā)數(shù)據(jù)給客戶(hù)端線程: " + Thread.currentThread().getName());
        //遍歷 所有注冊(cè)到selector 上的 SocketChannel,并排除 self
        for(SelectionKey key: selector.keys()) {
 
            //通過(guò) key  取出對(duì)應(yīng)的 SocketChannel
            Channel targetChannel = key.channel();
 
            //排除自己
            if(targetChannel instanceof  SocketChannel && targetChannel != self) {
                //轉(zhuǎn)型
                SocketChannel dest = (SocketChannel)targetChannel;
                //將msg 存儲(chǔ)到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //將buffer 的數(shù)據(jù)寫(xiě)入 通道
                dest.write(buffer);
            }
        }
    }
 
    public static void main(String[] args) {
        //創(chuàng)建服務(wù)器對(duì)象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
 
//可以寫(xiě)一個(gè)Handler
class MyHandler {
    public void readData() {
    }
    public void sendInfoToOtherClients(){
    }
}

客戶(hù)端代碼:

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.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
 
public class GroupChatClient {
 
    //定義相關(guān)的屬性
    private final String HOST = "127.0.0.1"; // 服務(wù)器的ip
    private final int PORT = 6667; //服務(wù)器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;
 
    //構(gòu)造器, 完成初始化工作
    public GroupChatClient() throws IOException {
 
        selector = Selector.open();
        //連接服務(wù)器
        socketChannel = socketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
        //設(shè)置非阻塞
        socketChannel.configureBlocking(false);
        //將channel 注冊(cè)到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok...");
 
    }
 
    //向服務(wù)器發(fā)送消息
    public void sendInfo(String info) {
 
        info = username + " 說(shuō):" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    //讀取從服務(wù)器端回復(fù)的消息
    public void readInfo() {
 
        try {
 
            int readChannels = selector.select();
            if(readChannels > 0) {//有可以用的通道
 
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
 
                    SelectionKey key = iterator.next();
                    if(key.isReadable()) {
                        //得到相關(guān)的通道
                       SocketChannel sc = (SocketChannel) key.channel();
                       //得到一個(gè)Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //讀取
                        sc.read(buffer);
                        //把讀到的緩沖區(qū)的數(shù)據(jù)轉(zhuǎn)成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //刪除當(dāng)前的selectionKey, 防止重復(fù)操作
            } else {
                //System.out.println("沒(méi)有可以用的通道...");
            }
 
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws Exception {
 
        //啟動(dòng)我們客戶(hù)端
        GroupChatClient chatClient = new GroupChatClient();
 
        //啟動(dòng)一個(gè)線程, 每隔3秒,讀取從服務(wù)器發(fā)送數(shù)據(jù)
        new Thread() {
            public void run() {
 
                while (true) {
                    chatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
 
        //發(fā)送數(shù)據(jù)給服務(wù)器端
        Scanner scanner = new Scanner(System.in);
 
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}

注意:必須設(shè)置通道為非阻塞,才能向Selector注冊(cè),否則報(bào) java.nio.channels.IllegalBlockingModeException 錯(cuò)
注意:在客戶(hù)端上要想獲取得到服務(wù)端的數(shù)據(jù),也需要注冊(cè)在register上(監(jiān)聽(tīng)讀事件)

上述就是小編為大家分享的Java NIO如何實(shí)現(xiàn)群聊系統(tǒng)了,如果剛好有類(lèi)似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI