Netty入门 - Netty应用实例-群聊系统

要实现一个简单的群聊系统,您可以使用 Netty 来处理客户端之间的通信。以下是一个基本的示例代码,演示了如何使用 Netty 创建一个简单的群聊系统:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.HashMap;
import java.util.Map;

public class GroupChatServer {
    private static final Map<String, ChannelHandlerContext> clients = new HashMap<>();
    private static final EventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(10);

    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline pipeline = ch.pipeline();
                     pipeline.addLast(eventExecutorGroup, new MessageDecoder(), new MessageEncoder(), new GroupChatServerHandler());
                 }
             });

            ChannelFuture f = b.bind(8080).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    static class GroupChatServerHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("Client connected: " + ctx.channel().remoteAddress());
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            Message message = (Message) msg;
            String content = message.getContent();
            if (message.getType() == MessageType.JOIN) {
                clients.put(content, ctx);
                System.out.println(content + " joined the chat.");
            } else if (message.getType() == MessageType.MESSAGE) {
                System.out.println("Received message from " + content + ": " + message.getText());
                broadcastMessage(content, message.getText());
            }
        }

        private void broadcastMessage(String sender, String message) {
            for (Map.Entry<String, ChannelHandlerContext> entry : clients.entrySet()) {
                if (!entry.getKey().equals(sender)) {
                    Message msg = new Message(MessageType.MESSAGE, sender, message);
                    entry.getValue().writeAndFlush(msg);
                }
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
}

在这个例子中,我们创建了一个简单的群聊系统。客户端发送加入聊天室的消息后,服务器会将其加入到客户端列表中,并在收到其他客户端的消息时广播给所有客户端。请注意,为了简化示例,我们省略了一些错误处理和边界情况的处理。在实际应用中,您需要根据具体需求进行更多的处理和优化。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值