NIO 实现群聊系统

服务器

java 复制代码
package chat;

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

/**
 * @author: zh
 * @create: 2023-09-13 10:52
 */
public class Server {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final int PORT = 666;

    public Server() throws IOException {
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void listen() throws IOException {
        while (true) {
            int count = selector.select();
            if (count > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        System.out.println(socketChannel.getRemoteAddress() + " up");
                    } else if (key.isReadable()) {
                        read(key);
                    }
                    iterator.remove();
                }
            }
        }
    }

    private void read(SelectionKey key) throws IOException {
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = socketChannel.read(buffer);
            if (count > 0) {
                String msg = new String(buffer.array());
                System.out.println(msg);
                send(msg, socketChannel);
            }
        } catch (Exception e) {
            System.out.println(socketChannel.getRemoteAddress() + " down");
            key.channel();
            socketChannel.close();
        }
    }

    private void send(String msg, SocketChannel self) throws IOException {
        System.out.println("send...");
        for (SelectionKey key : selector.keys()) {
            Channel channel = key.channel();
            if (channel instanceof SocketChannel && channel != self) {
                SocketChannel target = (SocketChannel) channel;
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                target.write(byteBuffer);
            }
        }
    }

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

客户端

java 复制代码
package chat;

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

/**
 * @author: zh
 * @create: 2023-09-13 11:25
 */
public class Client {
    private static final int PORT = 666;
    private static final String HOST = "127.0.0.1";
    private SocketChannel socketChannel;
    private Selector selector;
    private String username;

    public Client() throws IOException {
        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("ready");
    }

    private void send(String info) throws IOException {
        info = username + " say " + info;
        socketChannel.write(ByteBuffer.wrap(info.getBytes()));
    }

    private void read() throws IOException {
        int count = selector.select();
        if (count > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);
                    String msg = new String(buffer.array());
                    System.out.println(msg);
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client();
        new Thread(() -> {
            while (true) {
                try {
                    client.read();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String msg = scanner.nextLine();
            client.send(msg);
        }
    }
}
相关推荐
ZachOn1y8 天前
Java 入门指南:JVM(Java虚拟机)—— Java 内存运行时的数据区域
java·jvm·java-ee·团队开发·个人开发·nio
Flying_Fish_roe10 天前
java当中什么是NIO
java·开发语言·nio
CocoaAndYy10 天前
NIO、Reactor模式与直接内存
nio
FIN技术铺11 天前
问:聊一下NIO模型在Netty框架中的用法?
java·nio
FIN技术铺11 天前
问:你知道IO和NIO有哪些区别不?
java·nio
代码哲学12 天前
【BIO、NIO、AIO适用场景分析】
java·nio
漆黑的莫莫12 天前
经验笔记:RPC与高性能NIO框架
笔记·rpc·nio
G丶AEOM12 天前
还不懂BIO,NIO,AIO吗
java·nio
齐 飞16 天前
NIO笔记04-网络编程
java·网络·笔记·后端·nio
ZachOn1y17 天前
Java 入门指南:Java NIO —— Buffer(缓冲区)
java·后端·java-ee·团队开发·个人开发·nio