SocketServerHandler.java
1.92 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
package com.ruoyi.system.handler;
import com.ruoyi.system.protocol.ThinkraceUtil;
import com.ruoyi.system.strategy.CommandStrategy;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SocketServerHandler extends ChannelInboundHandlerAdapter {
CommandStrategy strategy;
private static final Logger log = LoggerFactory.getLogger(SocketServerHandler.class);
public SocketServerHandler() {
this.strategy = new CommandStrategy();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
// 处理指令
strategy.handler(buf.toString(CharsetUtil.UTF_8), ctx);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// System.out.println(ctx.channel().attr(AttributeKey.valueOf(ThinkraceUtil.IMEI)).get());
super.channelReadComplete(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
String imei = AttributeKey.valueOf(ThinkraceUtil.IMEI).toString();
// 发生异常触发
ThinkraceUtil.removeDevice(imei);
log.info("发生未知错误,设备:{}将关闭连接,原因:{}", imei, cause.getMessage());
ctx.close();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// ctx.channel().close();
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String imei = ctx.channel().attr(AttributeKey.valueOf(ThinkraceUtil.IMEI)).toString();
log.info("设备断开连接了,设备号为:{}", imei);
}
}