NettySendThread.java
2.38 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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;
}
}
}