NIO群聊

服务端

package nio;

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

public class Server {

    private static int SERVER_PORT = 9999;
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;

    public Server() throws Exception {
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        //ServerSocket socket = serverSocketChannel.socket();
        serverSocketChannel.socket().bind(new InetSocketAddress(SERVER_PORT));
        //selectionKey有四种状态, accept、connect、read、write
        //服务器的channel专门绑定事件为接收客户端连接的事件,只要有客户端连接,就可以感知到
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

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

    public void listen() {
        try {
            while (true) {
                //阻塞1秒钟返回绑定到选择器的selectionKey
                //判断选择器上是否有绑定的channel关联的selectionKey事件发生,且阻塞每1秒钟一次
                int count = selector.select(1000);
                if (count > 0) {
                    //选择器和channel绑定,selectionKey类似转换头,通过转换头可以获取到绑定的通道及buffer,此处获取selector上绑定的selectionKeys,
                    //通过selectionKey获取绑定的channel
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    //轮询每一个selectionKey,分别对应着channel
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        //如果key是有客户端连接, 如果是连接事件
                        if (key.isAcceptable()) {
                            //如果有客户端连接事件,就返回socketChannel
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            //客户端通道注册到选择器,且绑定事件为读事件
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + " 上线了...");
                        }

                        //如果通道事件是可读事件
                        if (key.isReadable()) {
                            readClient(key);
                        }
                        iterator.remove();
                    }
                } else {
                    //System.out.println("等待....");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    //读取到客户端消息
    public void readClient(SelectionKey key) throws Exception {
        SelectableChannel channel = null;
        SocketChannel socketChannel = null;
        try {
            channel = key.channel();
            socketChannel = (SocketChannel) channel;
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = socketChannel.read(buffer);
            if (count > 0) {
                String msg = new String(buffer.array());
                System.out.println("from client: " + msg.trim());

                //服务端接收到客户端的消息后,要将此消息转发给指定的channel, 排除自己
                sendMsgToOtherClient(msg, socketChannel);
            }
        } catch (IOException e) {
            try {
                System.out.println(socketChannel.getRemoteAddress() + "  离线了...");
                //取消注册
                key.cancel();
                //关闭通道
                socketChannel.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public void sendMsgToOtherClient(String msg, SocketChannel channel) throws Exception {
        System.out.println("服务端开始转发客户端的消息...  " + msg.trim());
        //selector.selectedKeys() 返回注册在selector中等待IO操作(及有事件发生)channel的selectionKey
        //selector.keys 返回当前所有注册在selector中的selectionKey,每个selectionKey关联一个channel
        //Set<SelectionKey> keys = selector.selectedKeys();
        Set<SelectionKey> keys = selector.keys();
        for (SelectionKey selectionKey : keys) {
            Channel targetChannel = selectionKey.channel();
            if (targetChannel instanceof SocketChannel && channel != targetChannel) {
                //转型为SocketChannel
                SocketChannel destChannel = (SocketChannel) targetChannel;
                //ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //把缓存区的数据都写入到其他通道中
                destChannel.write(buffer);
            }
        }
    }
    
}

客户端

package nio;

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 Client {

    private static final String IP = "127.0.0.1";
    private static final int SERVER_PORT = 9999;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public Client() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(IP,SERVER_PORT));
            socketChannel.configureBlocking(false);
            //socketChannel.bind(new InetSocketAddress(IP,SERVER_PORT));
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //向服务器发送消息
    public void sendInfo(String msg){
        try {
            String info = username + " 说 " + msg;
            //将消息写到channel中,服务器从通道里获取消息
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取从服务器端返回的消息
    public void receiveInfo(){
        try {
            //获取绑定到客户端通道channel的触发事件的数量
            int count = selector.select();
            if (count > 0){
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()){
                        SocketChannel channel = (SocketChannel)selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //buffer读取channel里的数据
                        channel.read(buffer);
                        //将buffer里的数据转为字符串类型
                        String msg = new String(buffer.array());
                        System.out.println("读取到服务器的数据是: "+msg.trim());
                    }
                }
                //删除当前selectionKey,防止重复操作
                iterator.remove();
            }else {
                //System.out.println("没有可以用的通道");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        new Thread(()->{
            while (true) {
                client.receiveInfo();
            }
        }).start();

        //发送数据
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String msg = scanner.nextLine();
            client.sendInfo(msg);
        }
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值