本文共 5151 字,大约阅读时间需要 17 分钟。
Netty 是一个高性能的异步I/O框架,广泛应用于网络服务器和客户端开发。本文将详细介绍基于Netty实现的聊天室项目结构,包括服务端、客户端以及相关的handler实现。
本项目主要包含以下几个部分:
服务端是Netty聊天室的核心,负责接收客户端连接并处理消息。
public class GroupChatServer { private int port; public GroupChatServer(int port) { this.port = port; } public void run() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<>()); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { new GroupChatServer(6666).run(); }} 服务端通过NioEventLoopGroup创建事件循环组,配置服务器Bootstrap,设置监听端口并处理连接。服务器启动后会监听指定端口,等待客户端连接。
public class GroupChatServerHandler extends SimpleChannelInboundHandler{ private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); channelGroup.writeAndFlush("[客户端] " + channel.remoteAddress() + " 加入聊天\n"); channelGroup.add(channel); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); channelGroup.writeAndFlush("[客户端] " + channel.remoteAddress() + " 离开了\n"); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println(ctx.channel().remoteAddress() + " 上线了~"); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println(ctx.channel().remoteAddress() + " 离线了~"); } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { Channel channel = ctx.channel(); channelGroup.forEach(ch -> { if (channel != ch) { ch.writeAndFlush("[用户] " + channel.remoteAddress() + " 发送了消息: " + msg + "\n"); } else { ch.writeAndFlush("[自己] 发送了消息: " + msg + "\n"); } }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); }}
服务端handler负责处理连接状态变化和消息传输。handlerAdded和handlerRemoved方法用于通知其他客户端用户状态变化。channelRead0方法负责读取消息并转发给所有在线客户端。
客户端负责连接到服务器并发送消息。
public class GroupChatClient { private final String host; private final int port; public GroupChatClient(String host, int port) { this.host = host; this.port = port; } public void run() throws InterruptedException { NioEventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<>()); ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); Channel channel = channelFuture.channel(); System.out.println("[" + channel.localAddress() + "] 服务器连接成功~"); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String msg = scanner.nextLine(); channel.writeAndFlush(msg + "\r\n"); } } finally { group.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { new GroupChatClient("localhost", 6666).run(); }} 客户端通过Bootstrap配置连接服务器,设置读写数据的handler,并处理用户输入。
public class GroupChatClientHandler extends SimpleChannelInboundHandler{ @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println(msg.trim()); }}
客户端handler负责处理接收到的消息,输出到控制台。
服务端(GroupChatServer)
客户端(GroupChatClient)
通用功能
本项目通过Netty框架实现了一个简单的聊天室功能,涵盖了服务端和客户端的开发,展示了Netty在高性能网络应用中的优势。通过灵活的handler机制,实现了用户状态通知和消息转发等功能。
转载地址:http://syxo.baihongyu.com/