package org.example;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 多聊客户端处理器
 * 继承自SimpleChannelInboundHandler,用于处理服务器发送的消息
 */
public class MultiChatClientHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 处理接收到的消息
     * @param ctx ChannelHandlerContext对象,表示当前处理器的上下文信息
     * @param msg 接收到的消息内容
     * @throws Exception 抛出异常
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg); // 打印接收到的消息
    }

    /**
     * 处理异常
     * @param ctx ChannelHandlerContext对象,表示当前处理器的上下文信息
     * @param cause 异常对象
     * @throws Exception 抛出异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace(); // 打印异常信息
        ctx.close(); // 关闭连接
    }
}
Netty实现多聊天室功能 - 客户端处理器详解

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

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