import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.concurrent.ConcurrentHashMap;

public class MultiChatServer {
    private final int port;
    private final ConcurrentHashMap<String, ChannelHandlerContext> userMap = new ConcurrentHashMap<>();
    private final EventExecutorGroup group = new DefaultEventExecutorGroup(16);

    public MultiChatServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new MultiChatServerHandler(userMap, group));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            System.out.println('Server started on port ' + port);
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new MultiChatServer(port).run();
    }
}

代码解释:

这段代码使用Netty框架实现了一个简单的多人聊天服务器。

  • 使用NIO模型实现高性能网络通信。
  • ServerBootstrap 用于配置和启动服务器。
  • EventLoopGroup 管理事件循环线程,处理客户端连接和IO事件。
  • ChannelInitializer 用于配置通道管道,添加 StringDecoderStringEncoder 编解码器处理字符串消息,以及自定义的 MultiChatServerHandler 处理业务逻辑。
  • MultiChatServerHandler 维护用户连接列表,并广播消息给所有在线用户。
  • 使用 EventExecutorGroup 提高并发处理能力。

功能:

  • 用户连接:客户端连接到服务器后,服务器会将其添加到用户列表中。
  • 消息广播:当服务器收到来自某个用户的消息时,会将该消息广播给所有其他在线用户。

使用Netty框架的优势:

  • 高性能:Netty基于NIO实现,能够处理大量并发连接。
  • 可扩展性:Netty的模块化设计使得开发者可以方便地扩展服务器功能。
  • 易用性:Netty提供了丰富的API,简化了网络编程的复杂性。
基于Netty的多人聊天服务器实现

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

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