/
IotNettyService.java
96 lines (83 loc) · 2.56 KB
/
IotNettyService.java
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package org.octopus.iot.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.octopus.iot.service.IotSensorService;
import org.octopus.iot.service.IotService;
@IocBean(create = "init", depose="close")
public class IotNettyService {
private static final Log log = Logs.get();
@Inject
Dao dao;
@Inject
IotService iotService;
@Inject
IotSensorService iotSensorService;
@Inject
IotNettyTcpServerInitializer iotNettyTcpServerInitializer;
@Inject
IotNettyUdpHandler iotNettyUdpHandler;
@Inject("java:$conf.get('netty.iot.tcp_port')")
int tcpPort;
@Inject("java:$conf.get('netty.iot.udp_port')")
int udpPort;
ServerBootstrap tcpBoot;
Bootstrap udpBoot;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
EventLoopGroup udpWorkGroup;
ChannelFuture tcpcf;
ChannelFuture udpcf;
public void init() throws InterruptedException {
if (tcpPort == 0 && udpPort == 0) {
log.info("tcpPort=0 and udpPort=0, socket proctol disable");
return;
}
bossGroup = new NioEventLoopGroup(2);
workerGroup = new NioEventLoopGroup();
udpWorkGroup = new NioEventLoopGroup();
if (tcpPort > 0) {
tcpBoot = new ServerBootstrap();
tcpBoot.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(iotNettyTcpServerInitializer);
tcpcf = tcpBoot.bind(tcpPort);
}
if (udpPort > 0) {
udpBoot = new Bootstrap();
udpBoot.group(udpWorkGroup)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.handler(iotNettyUdpHandler);
udpcf = udpBoot.bind(udpPort);
}
}
public void close() throws InterruptedException {
try {
if (tcpcf != null)
tcpcf.channel().close().sync();
if (udpcf != null)
udpcf.channel().close().sync();
} finally {
if (bossGroup != null)
bossGroup.shutdownGracefully().await();
if (workerGroup != null)
workerGroup.shutdownGracefully().await();
if (udpWorkGroup != null)
udpWorkGroup.shutdownGracefully().await();
}
}
}