Java NIO實現群聊系統

本文實例為大傢分享瞭Java NIO實現群聊系統的具體代碼,供大傢參考,具體內容如下

前面的文章介紹瞭NIO的三大核心組件並編寫瞭BIO的一個demo實例,本文使用NIO寫一個小應用實例,鞏固並加深對NIO的理解。

實例要求:

1)編寫一個 NIO 群聊系統,實現服務器端和客戶端之間的數據簡單通訊(非阻塞)
2)實現多人群聊
3)服務器端:可以監測用戶上線,離線,並實現消息轉發功能
4)客戶端:通過channel 可以無阻塞發送消息給其它所有用戶,同時可以接受其它用戶發送的消息(有服務器轉發得到)
5)目的:進一步理解NIO非阻塞網絡編程機制

服務端代碼:

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;
 
    //構造器
    //初始化工作
    public GroupChatServer() {
 
        try {
            //得到選擇器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel =  ServerSocketChannel.open();
            //綁定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //設置非阻塞模式
            listenChannel.configureBlocking(false);
            //將該listenChannel 註冊到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
 
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    //監聽
    public void listen() {
 
        System.out.println("監聽線程: " + Thread.currentThread().getName());
        try {
 
            //循環處理
            while (true) {
 
                int count = selector.select();
                if(count > 0) {//有事件處理
 
                    //遍歷得到selectionKey 集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        //取出selectionkey
                        SelectionKey key = iterator.next();
 
                        //監聽到accept
                        if(key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //將該 sc 註冊到seletor
                            sc.register(selector, SelectionKey.OP_READ);
                            //提示
                            System.out.println(sc.getRemoteAddress() + " 上線 ");
                        }
                        if(key.isReadable()) { //通道發送read事件,即通道是可讀的狀態
                            //處理讀 (專門寫方法..)
                            readData(key);
                        }
                        //當前的key 刪除,防止重復處理
                        iterator.remove();
                    }
 
                } else {
                    System.out.println("等待....");
                }
            }
 
        }catch (Exception e) {
            e.printStackTrace();
 
        }finally {
            //發生異常處理....
        }
    }
 
    //讀取客戶端消息
    private void readData(SelectionKey key) {
 
        //取到關聯的channle
        SocketChannel channel = null;
 
        try {
           //得到channel
            channel = (SocketChannel) key.channel();
            //創建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
 
            int count = channel.read(buffer);
            //根據count的值做處理
            if(count > 0) {
                //把緩存區的數據轉成字符串
                String msg = new String(buffer.array());
                //輸出該消息
                System.out.println("form 客戶端: " + msg);
                //向其它的客戶端轉發消息(去掉自己), 專門寫一個方法來處理
                sendInfoToOtherClients(msg, channel);
            }
 
        }catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 離線瞭..");
                //取消註冊
                key.cancel();
                //關閉通道
                channel.close();
            }catch (IOException e2) {
                e2.printStackTrace();;
            }
        }
    }
 
    //轉發消息給其它客戶(通道)
    private void sendInfoToOtherClients(String msg, SocketChannel self ) throws  IOException{
 
        System.out.println("服務器轉發消息中...");
        System.out.println("服務器轉發數據給客戶端線程: " + Thread.currentThread().getName());
        //遍歷 所有註冊到selector 上的 SocketChannel,並排除 self
        for(SelectionKey key: selector.keys()) {
 
            //通過 key  取出對應的 SocketChannel
            Channel targetChannel = key.channel();
 
            //排除自己
            if(targetChannel instanceof  SocketChannel && targetChannel != self) {
                //轉型
                SocketChannel dest = (SocketChannel)targetChannel;
                //將msg 存儲到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //將buffer 的數據寫入 通道
                dest.write(buffer);
            }
        }
    }
 
    public static void main(String[] args) {
        //創建服務器對象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
 
//可以寫一個Handler
class MyHandler {
    public void readData() {
    }
    public void sendInfoToOtherClients(){
    }
}

客戶端代碼:

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

註意:必須設置通道為非阻塞,才能向Selector註冊,否則報 java.nio.channels.IllegalBlockingModeException 錯
註意:在客戶端上要想獲取得到服務端的數據,也需要註冊在register上(監聽讀事件)

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: