ClientHandler.java 2.48 KB
package com.ruoyi.system.client;

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

import java.util.Scanner;

/**
 * 测试类 模拟手表设备
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {
//    @Override
//    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
//        ctx.writeAndFlush(Unpooled.copiedBuffer("IWAP00353456789012345#", CharsetUtil.UTF_8));
////        super.channelRegistered(ctx);
//    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        String str = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println("收到服务端" + ctx.channel().remoteAddress() + "的消息:" + byteBuf.toString(CharsetUtil.UTF_8));

        // 判断是否需要发送
        if (str.startsWith("IWBP12")) {
            String replace = str.replace(",353456789012345","").replace("IWBP12", "IWAP12");
            System.out.println("客户端响应" + ctx.channel().remoteAddress() + "的消息:" + byteBuf.toString(CharsetUtil.UTF_8));
            ctx.channel().writeAndFlush(Unpooled.copiedBuffer(replace, CharsetUtil.UTF_8));
        }
        if (str.startsWith("IWBP15")) {
            String replace = str.replace(",353456789012345","").replace("IWBP15", "IWAP15");
            System.out.println("客户端响应" + ctx.channel().remoteAddress() + "的消息:" + byteBuf.toString(CharsetUtil.UTF_8));
            ctx.channel().writeAndFlush(Unpooled.copiedBuffer(replace, CharsetUtil.UTF_8));
        }
//        else {
//            Scanner sc = new Scanner(System.in);
//            String line = sc.nextLine();
//            ctx.channel().writeAndFlush(Unpooled.copiedBuffer(line, CharsetUtil.UTF_8));
//        }
    }


//    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ctx.writeAndFlush(Unpooled.copiedBuffer("歪比巴卜~茉莉~Are you good~马来西亚~", CharsetUtil.UTF_8));
//    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("IWAP00353456789012345#", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
    }


}