首页>代码>Netty框架整合五种编解码示例>/netty-endecode/src/main/java/com/example/demo/client1/LinebaseClientHandler.java
package com.example.demo.client1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class LinebaseClientHandler extends ChannelInboundHandlerAdapter{
    
    private static int counter;
    
    private byte[] req;
    
    public LinebaseClientHandler(){
        //客户端发送信息需要加换行符,特别重要,否则服务端接收不到;
        req = ("current time:" + System.getProperty("line.separator")).getBytes();
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ByteBuf firstMessage = null;
        //连接成功后,发送消息,发送100吃,模拟信息发送的频繁
        for(int i = 0;i<100;i++){
            firstMessage = Unpooled.buffer(req.length);
            firstMessage.writeBytes(req);
            ctx.writeAndFlush(firstMessage);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg){
        try{
                        //此处已经LineBasedFrameDecoder、StringDecoder的解码,可以直接接收
            String body = (String) msg;
            System.out.println("now is:" + body + ";the counter is " + ++counter);
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    //释放资源
       ctx.close();
    }
}
最近下载更多
jaonsang  LV25 2022年4月8日
skipple3  LV39 2021年5月9日
wxm4252  LV12 2020年12月18日
zhengfei0421  LV6 2020年6月2日
mrj1314  LV7 2019年11月24日
Rommel  LV27 2019年10月28日
最代码官方  LV167 2019年10月26日
最近浏览更多
1909741473  LV8 2月19日
sunlzh888888  LV28 2023年9月12日
暂无贡献等级
yinyun1985  LV14 2022年10月31日
youwuzuichen  LV10 2022年10月28日
1358849392  LV21 2022年10月21日
Killah  LV9 2022年9月5日
no1xijin 2022年8月1日
暂无贡献等级
林间听风  LV10 2022年4月11日
xp95323  LV14 2022年1月25日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友