netty(七)Channel与线程实践
https://www.cnblogs.com/silyvin/p/9593368.html
本文验证了channel属于同一个线程的理论,建议不在handler中阻塞当前线程
客户端:
public class TimerClientHandler extends SimpleChannelInboundHandler<String> {
private int counter;
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("Now is : " + msg + "; the counter is:" + ++counter + " timestamp:" + (new Date()));
}
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf message = null;
for(int i=0; i<10; i++){
message = Unpooled.buffer(req.length);
message.writeBytes(req);
ctx.writeAndFlush(message);
TimeUnit.SECONDS.sleep(1);
}
}
}
public class TimerServerHandler extends SimpleChannelInboundHandler<String> {
private int counter;
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception{
System.out.println("Receive order :" + msg + ", the counter is : " + ++counter);
String currentTime = "QUERY TIME ORDER".equals(msg) ? new Date().toString() : "BAD ORDER";
currentTime = currentTime + System.getProperty("line.separator");
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
TimeUnit.SECONDS.sleep(1);
System.out.println("send response timestamp: " + new Date());
ctx.writeAndFlush(resp);
}
}
先说现象:
服务端每隔1s收到消息并打印,同时发回消息
客户端一次打印服务端发回的10条消息
解析:
客户端激活连接时,循环10次发送消息,期间阻塞1s,足足10s内该channel所在线程阻塞,无法处理read消息
10s后,服务端最后一条消息发送完毕,客户端active执行完毕,线程开始执行read,一次打印了所有10条消息

如果把服务端改成阻塞2秒
客户端这边:

前10s,active执行完毕,线程转到read,而此时服务端发回了5条消息,一次处理了5条,后10s,服务端每2s发送一条消息,客户端read每隔2s打印
浙公网安备 33010602011771号