‘liusuyi’
2023-06-25 0b25d230881ce4d56233a4834eb520d120f9a7a9
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
package com.ard.utils.tcp;
 
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
 
import javax.xml.bind.DatatypeConverter;
 
/**
 * @Description: tcp客户端处理
 * @ClassName: NettyTcpClientHandler
 * @Author: 刘苏义
 * @Date: 2023年06月25日17:02
 * @Version: 1.0
 **/
@Slf4j
public class NettyTcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg){
        // 处理接收到的消息
        byte[] byteArray = new byte[msg.readableBytes()];
        msg.getBytes(msg.readerIndex(), byteArray);
        String hexString = DatatypeConverter.printHexBinary(byteArray);
 
        log.info("Received: " + hexString);
    }
 
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 当客户端连接成功后,发送消息给服务器
        ByteBuf message = ctx.alloc().buffer();
        message.writeBytes("Hello, Server!".getBytes());
        ctx.writeAndFlush(message);
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        // 发生异常时的处理
        cause.printStackTrace();
        ctx.close();
    }
}