首页>代码>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();
}
}
最近下载更多
最近浏览更多
1909741473 LV8
2024年2月19日
sunlzh888888 LV29
2023年9月12日
微信网友_6491062177157120
2023年5月25日
暂无贡献等级
yinyun1985 LV14
2022年10月31日
youwuzuichen LV11
2022年10月28日
1358849392 LV21
2022年10月21日
Killah LV9
2022年9月5日
no1xijin
2022年8月1日
暂无贡献等级
林间听风 LV10
2022年4月11日
xp95323 LV15
2022年1月25日

