NettyReceiverHandler.java
2.31 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
package com.viontech.netty;
import com.viontech.configuration.PropertiesConfiguration;
import com.viontech.model.BaseModel;
import com.viontech.model.KeepAlive;
import com.viontech.model.LoginData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
/**
* @author 谢明辉
*/
@Slf4j
public class NettyReceiverHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
log.info("channelRegistered----------------");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof BaseModel) {
BaseModel message = (BaseModel) msg;
//注册命令
if (message instanceof LoginData) {
BaseModel result = new BaseModel().setDeviceId(0L).setLength(16L).setProtocol(0x00020100L);
LoginData logindata = (LoginData) message;
Long deviceId = logindata.getDeviceId();
if (PropertiesConfiguration.username.equals(logindata.getUsername()) &&
PropertiesConfiguration.password.equals(logindata.getPassword())) {
log.info("注册成功");
ChannelGroup.registered(deviceId, ctx.channel());
result.setFlag(0L);
} else {
log.info("注册失败,用户名:[{}],密码:[{}]", logindata.getUsername(), logindata.getPassword());
result.setFlag(1L);
}
ctx.writeAndFlush(result).await();
} else if (message instanceof KeepAlive) {
log.info("收到心跳,设备ID:[{}]", message.getDeviceId());
}
ReferenceCountUtil.release(msg);
ctx.fireChannelReadComplete();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
cause.printStackTrace();
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
log.info("断开连接:{}", ctx.channel().id().toString());
}
}