NettySendThread.java 2.38 KB
package cn.com.glsx.notify.netty;

import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import com.glsx.plat.common.utils.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalTime;

@Slf4j
public class NettySendThread implements Runnable {

    private ChannelHandlerContext ctx;

    private Object data;

    public NettySendThread(ChannelHandlerContext ctx, Object data) {
        this.ctx = ctx;
        this.data = data;
    }

    @Override
    public void run() {
        if (data instanceof ByteBuf) {
            //将 msg 转成一个 ByteBuf
            //ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
            ByteBuf buf = (ByteBuf) data;
            //得到此时客户端的数据长度
            int bytes_length = buf.readableBytes();
            //组件新的字节数组
            byte[] buffer = new byte[bytes_length];
            buf.readBytes(buffer);
            String allData = NettyByteAndStringUtils.byteToHex(buffer);
            log.info("进入服务端数据:" + allData);

            String reply = NettyDataService.sendData(allData);
            log.info("接收需要返回的消息:" + reply);
            if (StringUtils.isNullOrEmpty(reply)) {
                return;
            }

            //数据的发送与接收都是16进制
            byte[] sendData = NettyByteAndStringUtils.hexToByte(reply);
            log.info("发送数据时间: " + LocalTime.now());
            ctx.writeAndFlush(sendData);
        } else if (data instanceof TextWebSocketFrame) {
            TextWebSocketFrame frame = (TextWebSocketFrame) data;
            String allData = frame.text();
            log.info("进入服务端数据:" + allData);

            String reply = null;
            if ("你好".equals(allData)) {
                reply = "你好";
            }
            if ("在干吗".equals(allData)) {
                reply = "学习";
            }
            if (StringUtils.isNullOrEmpty(reply)) {
                return;
            }

            TextWebSocketFrame webSocketFrame = new TextWebSocketFrame(reply);
            //写回数据也是按照协议格式写TextWebSocketFrame
            ctx.writeAndFlush(webSocketFrame);
        } else {
            return;
        }
    }
}