NIO-03 多人聊天

多人聊天

server


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;


public class ChatServer {
    // 1. 定義屬性
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final String HOST = "localhost";
    private static final int PORT = 6667;

    public ChatServer() {

        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();

            serverSocketChannel.socket().bind(new InetSocketAddress(HOST, PORT));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // eg: 監(jiān)聽
    public void listen() {

        try {

            while (true) {

                int count = selector.select(2000);
                if (count > 0) {
                    Set<SelectionKey> selectedKeys = selector.selectedKeys();

                    Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

                    while (keyIterator.hasNext()) {
                        SelectionKey key = keyIterator.next();

                        if (key.isAcceptable()) {

                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);

                            System.out.println(socketChannel.getRemoteAddress() + "....eg: 上線了...");
                        }

                        if (key.isReadable()) {// eg: 通道發(fā)送read事件
                            // eg: 處理讀取
                            System.out.println("處理讀數(shù)據(jù)....");
                            
                            //readData
                            readData(key);

                        }

                        // eg: 刪除當(dāng)前key
                        keyIterator.remove();
                    }

                } else {
                    System.out.println("等待...");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readData(SelectionKey key) {
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) key.channel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            int read = socketChannel.read(byteBuffer);
            // eg: 根據(jù) read 讀取的數(shù)據(jù)做
            if (read > 0) {
                // eg: 把緩存數(shù)據(jù)轉(zhuǎn)換成字符串
                String msg = new String(byteBuffer.array());

                System.out.println("from client:" + msg);

                // eg: 向其他客戶端轉(zhuǎn)發(fā)消息,專門處理
                sendInfoToOthers(msg,socketChannel);
            }

        } catch (Exception e) {
            try {
                System.out.println(socketChannel.getRemoteAddress()+"下線了...");
                key.cancel();
                socketChannel.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            
        }
    }

    // eg: 向其他客戶端轉(zhuǎn)發(fā)消息,專門處理
    public void sendInfoToOthers(String msg, SocketChannel self) throws Exception {
        System.out.println("sendInfoToOthers....");

        Set<SelectionKey> keys = selector.keys();
        for (SelectionKey selectionKey : keys) {

            SelectableChannel channel = selectionKey.channel();
            if (channel instanceof SocketChannel && self != channel) {
                SocketChannel sc = (SocketChannel) channel;
                
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                sc.write(wrap);
            }
        }
    }

    public static void main(String[] args) {
        ChatServer server = new ChatServer();
        server.listen();
    }
}

client


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 ChatClient {
    // 1. 定義屬性
    private Selector selector;
    private String username;
    private SocketChannel socketChannel;
    private static final String HOST = "localhost";
    private static final int PORT = 6667;

    public ChatClient() {

        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println("username:" + username);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //eg: 向服務(wù)器發(fā)送消息
    public void sendMsg2Server(String info) {
        
        info = username +" : "+ info;   
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    //eg: 讀取從服務(wù)器回復(fù)的消息
    public void readInfo() {
        
        try {
            
            int select = selector.select();
            if(select > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if(selectionKey.isReadable()) {
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        channel.read(buffer);
                        
                        //eg: 把讀取到的數(shù)據(jù)轉(zhuǎn)換成字符串
                        System.out.println(new String(buffer.array()));
                    }
                }
                // 這里應(yīng)該移除這個(gè)key
                iterator.remove();
            }else {

            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    
    public static void main(String[] args) {
        ChatClient client = new ChatClient();
        
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    client.readInfo();
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            };
        }.start();
        
        
        Scanner scanner = new Scanner(System.in);
        
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            client.sendMsg2Server(msg);
            
        }
        
        scanner.close();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容