博客
关于我
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/

    你可能感兴趣的文章
    Objective-C实现multiplesThreeAndFive三或五倍数的算法 (附完整源码)
    查看>>
    Objective-C实现n body simulationn体模拟算法(附完整源码)
    查看>>
    Objective-C实现naive string search字符串搜索算法(附完整源码)
    查看>>
    Objective-C实现natural sort自然排序算法(附完整源码)
    查看>>
    Objective-C实现nested brackets嵌套括号算法(附完整源码)
    查看>>
    Objective-C实现nevilles method多项式插值算法(附完整源码)
    查看>>
    Objective-C实现newtons second law of motion牛顿第二运动定律算法(附完整源码)
    查看>>
    Objective-C实现newton_raphson牛顿拉夫森算法(附完整源码)
    查看>>
    Objective-C实现NLP中文分词(附完整源码)
    查看>>
    Objective-C实现NLP中文分词(附完整源码)
    查看>>
    Objective-C实现not gate非门算法(附完整源码)
    查看>>
    Objective-C实现number of digits解字符数算法(附完整源码)
    查看>>
    Objective-C实现NumberOfIslands岛屿的个数算法(附完整源码)
    查看>>
    Objective-C实现numerical integration数值积分算法(附完整源码)
    查看>>
    Objective-C实现n皇后问题算法(附完整源码)
    查看>>
    Objective-C实现O(E + V) 中找到 0-1-graph 中的最短路径算法(附完整源码)
    查看>>
    Objective-C实现OCR文字识别(附完整源码)
    查看>>
    Objective-C实现odd even sort奇偶排序算法(附完整源码)
    查看>>
    Objective-C实现ohms law欧姆定律算法(附完整源码)
    查看>>
    Objective-C实现P-Series algorithm算法(附完整源码)
    查看>>