NIO 实现简单群聊功能

服务端:

package com.yang.runnable;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChat {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final int port=8801;

    public GroupChat() {
        try {
            selector=Selector.open();
            serverSocketChannel=ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(port));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() throws IOException {

        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if(key.isAcceptable()){
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel)key.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ);
                    String userName = socketChannel.getRemoteAddress().toString();
                    System.out.println(userName+": 上线了。。。。。");
                }
                if(key.isReadable()){
                    SocketChannel sc = (SocketChannel)key.channel();
                    boolean flgRead = read(sc);
                    if(!flgRead){
                        System.out.println(sc.getRemoteAddress().toString()+"下线了。。。");
                        key.cancel();
                    }
                }
                iterator.remove();
            }
        }
    }

    public boolean read(SocketChannel socketChannel) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int read = socketChannel.read(buffer);
        if(read==-1){
            return false;
        }
        String msg = new String(buffer.array());
        String userName = socketChannel.getRemoteAddress().toString();
        System.out.println("收到"+userName+"发来的消息:"+msg);
        dispatchet(socketChannel,msg);
        return true;
    }

    public void dispatchet(SocketChannel socketChannel,String msg){
        Iterator<SelectionKey> iterator = selector.keys().iterator();
        while (iterator.hasNext()){
            SelectionKey selectionKey = iterator.next();
            SelectableChannel channel = selectionKey.channel();
            if(channel instanceof  SocketChannel && channel!=socketChannel){
                SocketChannel sc=(SocketChannel)channel;
                try {
                    sc.write(ByteBuffer.wrap(msg.getBytes()));
                } catch (IOException e) {
                    try {
                        System.out.println(sc.getRemoteAddress().toString()+"下线了。。。");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    selectionKey.cancel();
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) throws IOException {
        GroupChat groupChat = new GroupChat();
        groupChat.listen();
    }

}


客户端:

package com.yang.xiao.hui;

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;

public class SocketClient {
    private Selector selector;
    private SocketChannel socketChannel;
    private static final int port=8801;

    public SocketClient() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1",port));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void sendMessage(String message){
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        try {
            System.out.println("向服务端发送。。。。"+message);
            socketChannel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void listen(){
        try {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if(key.isReadable()){
                    SocketChannel channel =(SocketChannel) key.channel();
                    ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                    channel.read(byteBuffer);
                    System.out.println("收到服务器返回的:"+new String(byteBuffer.array()));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static void main(String[] args) {
        SocketClient socketClient = new SocketClient();
        new Thread(()->{
            while (true){
                socketClient.listen();
            }

        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String message = scanner.next();
            socketClient.sendMessage(message);
        }

    }


}

 

posted @ 2020-07-01 10:11  yangxiaohui227  阅读(217)  评论(0)    收藏  举报