Java NIO實現聊天室功能

本文實例為大傢分享瞭Java NIO實現聊天室功能的具體代碼,供大傢參考,具體內容如下

代碼裡面已經包含瞭必要的註釋,這裡不詳述瞭。實現瞭基本的聊天室功能。

常量類:

public class Constant {
    public static final int serverPort = 44444;
}

服務端:

package server;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;
 
import constant.Constant;
 
public class SocketServer {
    private Charset charset = Charset.forName("UTF-8");
    private ServerSocketChannel serverSocketChannel;
    private Selector serverSocketSelector;
    private SelectionKey serverRegisterKey;
    private ByteBuffer buffer = ByteBuffer.allocate(1024);
 
    public static void main(String[] args) throws IOException {
        new SocketServer().openServer(new InetSocketAddress(Constant.serverPort));
    }
 
    public void openServer(SocketAddress address) throws IOException {
        init(address);
        handle();
    }
 
    private void init(SocketAddress address) throws IOException {
        serverSocketSelector = Selector.open();
 
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverRegisterKey = serverSocketChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
 
        serverSocketChannel.socket().bind(address);
    }
 
    private void handle() throws IOException {
        System.out.println("服務端open");
        while (serverSocketSelector.select() > 0) {
            Iterator<SelectionKey> iterator = serverSocketSelector.selectedKeys().iterator();
 
            // 為什麼這裡要用迭代器,而不用增強for循環之類的呢?是因為這裡獲得一個key之後,要對其進行移除,避免二次處理,造成影響
            while (iterator.hasNext()) {
                dispatch(iterator.next());
                iterator.remove();
            }
        }
    }
 
    private void dispatch(SelectionKey key) throws IOException {
        if (key.isAcceptable()) {
            accept(key);
        } else if (key.isReadable()) {
            readMessage(key);
        } else if (key.isValid() && key.isWritable()) {
            writeMessage(key);
        }
    }
 
    private void accept(SelectionKey key) throws IOException, ClosedChannelException {
        // 主要的是,接收事件是發生在服務器這邊的,所以這邊的通道要強轉為ServerSocketChannel
        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        SocketChannel client = server.accept();
        client.configureBlocking(false);
        // 同時再給該通道註冊選擇器,監聽的內容的讀取
        client.register(serverSocketSelector, SelectionKey.OP_READ);
    }
 
    private void readMessage(SelectionKey key) throws IOException {
        SocketChannel client = (SocketChannel) key.channel();
        client.read(buffer);
        // 調整為讀取模式
        buffer.flip();
        String content = charset.decode(buffer).toString();
        // 壓縮空間,即拋棄已經讀取的內容(實際上還在裡面,隻是處於等待被覆蓋狀態)
        buffer.compact();
        // 這裡可以根據業務邏輯,設置不設置都可以,但是這裡想接受到消息後立馬回復一條消息,所以設置下一次感興趣的(監聽)事件為寫
        key.interestOps(SelectionKey.OP_WRITE);
        // 設置系統回復信息
        key.attach("系統已經收到你的消息\n");
        // 開始廣播這個客戶端的內容到其他客戶端
        broadcast(key, content);
    }
 
    private void broadcast(SelectionKey self, String content) throws IOException {
        Set<SelectionKey> selectedKeys = self.selector().keys();
        for (SelectionKey key : selectedKeys) {
 
            // 不能發送給自己,也不要服務器自己本身對這個有反應
            if (key != self && key != serverRegisterKey) {
                String oldMessage = (String) key.attach(null);
                // 如果有舊消息的話,在下一次發送時,連同舊消息一起發送
                key.attach(oldMessage != null ? oldMessage + content : content);
                key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            }
        }
    }
 
    private void writeMessage(SelectionKey key) throws IOException {
        SocketChannel client = (SocketChannel) key.channel();
        // 獲取發給這個客戶端的消息,並清空消息
        client.write(charset.encode((String) key.attach(null)));
        key.interestOps(SelectionKey.OP_READ);
    }
}

客戶端(包含瞭Socket版本和SocketChannel版本):

package client;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;
 
import constant.Constant;
 
public class SocketClient {
 
    public static void main(String[] args) throws IOException {
        nioVersion();
        // ioVersion();
    }
 
    private static void ioVersion() throws UnknownHostException, IOException {
        System.out.println("客戶端");
        final Socket socket = new Socket();
        socket.connect(new InetSocketAddress(Constant.serverPort));
 
        new Thread() {
            @Override
            public void run() {
                Scanner scanner = new Scanner(System.in);
 
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    try {
                        socket.getOutputStream().write((line + "\n").getBytes("UTF-8"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                scanner.close();
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            };
        }.start();
 
        new Thread() {
            @Override
            public void run() {
                try {
                    Scanner scanner = new Scanner(socket.getInputStream(), "utf-8");
                    while (scanner.hasNext()) {
                        String line = scanner.nextLine();
                        System.out.println("收到消息:" + line);
                    }
                    scanner.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
 
            }
        }.start();
    }
 
    private static void nioVersion() throws IOException {
        Charset charset = Charset.forName("UTF-8");
 
        System.out.println("客戶端");
        SocketChannel socketChannel = SocketChannel.open();
        // 設置為非阻塞模式
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(Constant.serverPort));
 
        while (true) {
            if (socketChannel.finishConnect()) {
                new Thread() {
                    @Override
                    public void run() {
                        Scanner scanner = new Scanner(System.in);
                        while (scanner.hasNext()) {
                            String input = scanner.nextLine();
 
                            try {
                                socketChannel.write(charset.encode(input));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
 
                        }
                        scanner.close();
                    }
                }.start();
 
                new Thread() {
                    ByteBuffer dst = ByteBuffer.allocate(1024);
 
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                int len = socketChannel.read(dst);
                                if (len > 0) {
                                    dst.flip();
                                    System.out.println("收到消息:" + charset.decode(dst));
                                    dst.compact();
                                }
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();
                return;
            }
        }
    }
 
}

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

推薦閱讀: