博客
关于我
Netty聊天室案例
阅读量:292 次
发布时间:2019-03-01

本文共 5151 字,大约阅读时间需要 17 分钟。

Netty聊天室项目结构与实现

Netty 是一个高性能的异步I/O框架,广泛应用于网络服务器和客户端开发。本文将详细介绍基于Netty实现的聊天室项目结构,包括服务端、客户端以及相关的handler实现。

项目结构概述

本项目主要包含以下几个部分:

1. 服务端(GroupChatServer)

服务端是Netty聊天室的核心,负责接收客户端连接并处理消息。

1.1 Server类

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,设置监听端口并处理连接。服务器启动后会监听指定端口,等待客户端连接。

1.2 ServerHandler类

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方法负责读取消息并转发给所有在线客户端。


2. 客户端(GroupChatClient)

客户端负责连接到服务器并发送消息。

2.1 Client类

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,并处理用户输入。

2.2 ClientHandler类

public class GroupChatClientHandler extends SimpleChannelInboundHandler
{ @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println(msg.trim()); }}

客户端handler负责处理接收到的消息,输出到控制台。


项目总体架构

  • 服务端(GroupChatServer)

    • 启动一个NioEventLoopGroup,配置服务器Bootstrap。
    • 配置监听端口,设置SO_BACKLOG和SO_KEEPALIVE选项。
    • 自定义ChannelInitializer,注册StringDecoder和StringEncoder。
    • 自定义handler处理连接状态和消息传输。
  • 客户端(GroupChatClient)

    • 启动一个NioEventLoopGroup,配置Bootstrap。
    • 连接到服务器,注册自定义handler。
    • 读取用户输入并发送消息。
  • 通用功能

    • 连接状态通知:handlerAdded和handlerRemoved方法用于通知其他客户端用户状态变化。
    • 消息转发:channelRead0方法读取消息并转发给所有在线客户端。
    • 异常处理:exceptionCaught方法用于处理异常,关闭通道。

  • 项目优势

  • 高效异步I/O:Netty基于异步I/O框架,处理大规模并发连接更高效。
  • 可扩展性:支持多个客户端同时在线,消息转发机制灵活。
  • 简化开发:通过ChannelPipeline和自定义handler,简化网络通信逻辑。

  • 总结

    本项目通过Netty框架实现了一个简单的聊天室功能,涵盖了服务端和客户端的开发,展示了Netty在高性能网络应用中的优势。通过灵活的handler机制,实现了用户状态通知和消息转发等功能。

    转载地址:http://syxo.baihongyu.com/

    你可能感兴趣的文章
    python 启动提示IDLE's subprocess didn't make conne...
    查看>>
    python 命令接口_实现“[命令][操作][参数]”样式的命令行接口?
    查看>>
    Python 和 OpenCV.如何检测图像中的所有(填充)圆形/圆形对象?
    查看>>
    Python 和 RabbitMQ - 聆听来自多个渠道的消费事件的最佳方式?
    查看>>
    python编辑器打不开_关于命令ride.py打不开RF,而是打开pycharm编辑器问题解决思路...
    查看>>
    python编译exe同时支持32位_第三周:同时管理64位和32位版本的Python,并用Pyinstaller打包成exe...
    查看>>
    Python 和Java 哪个更适合做自动化测试?
    查看>>
    Python编程:掌握高级语言程序设计。从零基础到精通,收藏这篇就够了!
    查看>>
    python 图片转ico
    查看>>
    python 图片转文字、语音转文字、文字转语音保存音频并朗读
    查看>>
    python 在包含类似字符\x16、\x12、\x某某的数组中将以\x开头的字符找出来的方法
    查看>>
    Python 在并行进程之间共享字典
    查看>>
    Python 垃圾收集器文档
    查看>>
    python 基于 wordcloud + jieba + matplotlib 生成词云
    查看>>
    python 基于detectron或mask_rcnn的mask遮罩区域进行图片截取
    查看>>
    Python编程:Tkinter图形界面设计(2)
    查看>>
    Python 基础 - Day 5 Learning Note - 模块 之 标准库:time (1)
    查看>>
    Python 基础一
    查看>>
    python 基础操作知识整理总结
    查看>>
    Python 基础知识点整理与分享,期盼你的交流!
    查看>>