shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.walker.tcp.netty;
 
import com.walker.tcp.connect.LongConnection;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
 
/**
 * 使用netty实现的通信处理handler,该handler调用的方法通过自己的handler来适配处理。
 * @author 时克英
 * @date 2018-08-16
 *
 */
@Sharable
public class DefaultLongHandler extends AbstractChannelInBoundHandler<Object> {
//public class DefaultLongHandler extends AbstractChannelInBoundHandler<String> {
 
     @Override
     protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
//          // 收到消息直接打印输出
//         System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);
//         // 返回客户端消息 - 我已经接收到了你的消息
//          ctx.writeAndFlush("Received your message !\n");
//          System.out.println("通道id = " + ctx.channel().id().asLongText() + ", " + ctx.channel().id().asShortText());
         String message = msg == null ? null : msg.toString();
 
         String id = ctx.channel().id().asLongText() ;
         LongConnection conn = (LongConnection)connectionManager.getConnection(id);
         msgThreadLocal.set(message);
 
         tcpServerHandler.onRead(conn, message);
      }
 
     @Override
     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//         System.out.println("服务端读取完成数据一次。" + ctx.channel().remoteAddress() );
 
         String id = ctx.channel().id().asLongText() ;
         Object msg = msgThreadLocal.get();
 
         tcpServerHandler.onReadComplete(msg, id, ctx);
         msgThreadLocal.set(null);
         super.channelReadComplete(ctx);
     }
 
}