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;

//客户端
public class MultiChatClient {
    private final String host;
    private final int port;
    private ChannelHandlerContext ctx;

    // 构造函数,初始化主机和端口
    public MultiChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    // 客户端运行方法
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // 添加解码器和编码器,以及客户端处理程序
                            ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new MultiChatClientHandler());
                        }
                    });
            // 连接到服务器
            ChannelFuture f = b.connect(host, port).sync();
            ctx = f.channel().pipeline().context(MultiChatClientHandler.class);
            // 从控制台读取输入,并将其发送到服务器
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }
                if (line.equals('LIST')) {
                    String username = null;
                    ctx.writeAndFlush(line + '|' + username + '
');
                } else {
                    ctx.writeAndFlush(line + '
');
                }
            }
        } finally {
            // 关闭事件循环组
            group.shutdownGracefully();
        }
    }

    // 主方法,创建客户端实例并运行
    public static void main(String[] args) throws Exception {
        String host = 'localhost';
        int port = 8080;
        new MultiChatClient(host, port).run();
    }
}

代码解释:

这段代码使用 Netty 框架实现了一个简单的多人聊天室客户端。

主要功能:

  1. 连接服务器: 客户端通过 Bootstrap 类连接到指定主机和端口的服务器。
  2. 发送消息: 客户端使用 ChannelHandlerContext 发送消息到服务器。
  3. 接收消息: 客户端通过 MultiChatClientHandler 处理接收到的服务器消息。

代码说明:

  • MultiChatClient 类: 客户端主类,负责连接服务器、发送消息和接收消息。
  • run() 方法: 启动客户端,连接服务器,并循环读取用户输入发送到服务器。
  • main() 方法: 程序入口,创建 MultiChatClient 实例并运行。
  • MultiChatClientHandler (未在代码中展示): 用于处理接收到的服务器消息,并将其打印到控制台。

使用说明:

  1. 你需要先启动一个聊天室服务器。
  2. 运行该客户端代码,连接到服务器。
  3. 在控制台输入消息,即可发送到服务器,并被其他客户端接收到。

注意: 你需要根据实际情况修改服务器地址和端口号。

基于Netty的多人聊天室客户端实现

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

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