package org.example;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 基于Netty的多人聊天室客户端
 */
public class MultiChatClient {
    private final String host; // 服务器主机名
    private final int port; // 服务器端口号
    private ChannelHandlerContext ctx; // 用于与服务器通信的ChannelHandlerContext

    /**
     * 构造函数
     * @param host 服务器主机名
     * @param port 服务器端口号
     */
    public MultiChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 运行客户端
     * @throws Exception
     */
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup(); // 创建一个NioEventLoopGroup对象用于处理I/O操作
        try {
            Bootstrap b = new Bootstrap(); // 创建一个Bootstrap对象用于配置客户端
            b.group(group) // 设置EventLoopGroup
                    .channel(NioSocketChannel.class) // 指定使用NioSocketChannel作为客户端通道的实现
                    .option(ChannelOption.SO_KEEPALIVE, true) // 设置TCP连接的KeepAlive选项为true
                    .handler(new ChannelInitializer<SocketChannel>() { // 设置ChannelInitializer用于初始化通道
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // 添加StringDecoder、StringEncoder和MultiChatClientHandler到通道的pipeline中
                            ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new MultiChatClientHandler());
                        }
                    });

            // 连接服务器并获取ChannelFuture对象
            ChannelFuture f = b.connect(host, port).sync(); 
            // 获取MultiChatClientHandler的ChannelHandlerContext对象
            ctx = f.channel().pipeline().context(MultiChatClientHandler.class); 
            // 创建一个BufferedReader用于读取用户输入的消息
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                // 读取用户输入的消息
                String line = in.readLine(); 
                // 如果输入的消息为空,则退出循环
                if (line == null) {
                    break;
                }

                // 发送消息给服务器
                ctx.writeAndFlush(line + '\n'); 
            }
        } finally {
            // 关闭线程组
            group.shutdownGracefully(); 
        }
    }

    /**
     * 主函数
     * @param args 命令行参数
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String host = 'localhost'; // 设置服务器主机名
        int port = 8080; // 设置服务器端口号
        // 创建客户端实例并运行
        new MultiChatClient(host, port).run(); 
    }
}
基于Netty的多人聊天室客户端代码示例

原文地址: https://www.cveoy.top/t/topic/f3Ac 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录