|
@@ -23,21 +23,17 @@ import lombok.extern.slf4j.Slf4j;
|
|
|
*/
|
|
|
@Slf4j
|
|
|
public class IotSocketClient {
|
|
|
-
|
|
|
- public static final EventLoopGroup GROUP = new NioEventLoopGroup(1);
|
|
|
-
|
|
|
- public static final Bootstrap BS = new Bootstrap();
|
|
|
-
|
|
|
- static {
|
|
|
- // 注册线程池、使用NioSocketChannel来作为连接用的channel类
|
|
|
- BS.group(GROUP).channel(NioSocketChannel.class);
|
|
|
- }
|
|
|
|
|
|
public static boolean connectAndSend(String host, int port, String command) {
|
|
|
+ EventLoopGroup group = new NioEventLoopGroup(1);
|
|
|
+ Bootstrap bs = new Bootstrap();
|
|
|
+ // 注册线程池、使用NioSocketChannel来作为连接用的channel类
|
|
|
+ bs.group(group).channel(NioSocketChannel.class);
|
|
|
+
|
|
|
boolean result = false;
|
|
|
ChannelFuture cf = null;
|
|
|
try {
|
|
|
- BS.remoteAddress(new InetSocketAddress(host, port)) // 绑定连接端口和host信息
|
|
|
+ bs.remoteAddress(new InetSocketAddress(host, port)) // 绑定连接端口和host信息
|
|
|
.handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
|
|
|
@Override
|
|
|
protected void initChannel(SocketChannel ch) throws Exception {
|
|
@@ -48,7 +44,7 @@ public class IotSocketClient {
|
|
|
}
|
|
|
});
|
|
|
|
|
|
- cf = BS.connect().sync(); // 异步连接服务器
|
|
|
+ cf = bs.connect().sync(); // 异步连接服务器
|
|
|
log.info("服务端连接成功...");
|
|
|
|
|
|
result = true;
|
|
@@ -63,6 +59,10 @@ public class IotSocketClient {
|
|
|
log.error("未知异常", e2);
|
|
|
}
|
|
|
}
|
|
|
+ if (group != null) {
|
|
|
+ group.shutdownGracefully();
|
|
|
+ log.info("线程池已关闭..");
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
return result;
|