|
|
@ -56,6 +56,7 @@ public class TcpClient { |
|
|
|
@Override |
|
|
|
protected void initChannel(Channel ch) { |
|
|
|
ch.pipeline().addLast(deviceMessageHandler); |
|
|
|
ch.pipeline().addLast(new TcpConnectionHandler()); |
|
|
|
} |
|
|
|
}); |
|
|
|
} |
|
|
@ -86,12 +87,14 @@ public class TcpClient { |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
public void send(String request) { |
|
|
|
public boolean send(String request) { |
|
|
|
if (channel != null && channel.isActive()) { |
|
|
|
ByteBuf byteBuf = Unpooled.copiedBuffer(request, CharsetUtil.UTF_8); |
|
|
|
channel.writeAndFlush(byteBuf); |
|
|
|
return true; |
|
|
|
} else { |
|
|
|
log.error("TCP服务未连接,无法发送请求: {}", request); |
|
|
|
return false; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
@ -103,8 +106,11 @@ public class TcpClient { |
|
|
|
CompletableFuture<DeviceFeedback> future = new CompletableFuture<>(); |
|
|
|
responseMap.put(request.getId(), future); |
|
|
|
try { |
|
|
|
this.send(JSONUtil.toJsonStr(request)); |
|
|
|
return future.get(tcpConfig.getFeedbackTimeout(), TimeUnit.MILLISECONDS); // 等待 FEEDBACK 响应 |
|
|
|
if(this.send(JSONUtil.toJsonStr(request))){ |
|
|
|
return future.get(tcpConfig.getFeedbackTimeout(), TimeUnit.MILLISECONDS); // 等待 FEEDBACK 响应 |
|
|
|
}else{ |
|
|
|
return null; |
|
|
|
} |
|
|
|
} catch (Exception e) { |
|
|
|
log.error("发送TCP指令错误 {}", JSONUtil.toJsonStr(request), e); |
|
|
|
} finally { |
|
|
@ -122,4 +128,24 @@ public class TcpClient { |
|
|
|
log.error("未找到 requestId: {} 对应的等待请求", requestId); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
private class TcpConnectionHandler extends ChannelInboundHandlerAdapter { |
|
|
|
|
|
|
|
@Override |
|
|
|
public void channelInactive(ChannelHandlerContext ctx) throws Exception { |
|
|
|
// 连接断开时的处理逻辑 |
|
|
|
log.error("TCP连接丢失,准备重新连接..."); |
|
|
|
if (channel != null) { |
|
|
|
channel.close(); |
|
|
|
} |
|
|
|
connect(); |
|
|
|
super.channelInactive(ctx); |
|
|
|
} |
|
|
|
|
|
|
|
@Override |
|
|
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { |
|
|
|
log.error("TCP连接发生异常: {}", cause.getMessage(), cause); |
|
|
|
ctx.close(); |
|
|
|
} |
|
|
|
} |
|
|
|
} |