From b73493029d17c1542119fa42d19e328e08f291fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E5=87=A4=E5=90=89?= Date: Thu, 20 Feb 2025 17:28:13 +0800 Subject: [PATCH] =?UTF-8?q?fix:TCP=E9=80=9A=E4=BF=A1=E5=A2=9E=E5=8A=A0Json?= =?UTF-8?q?ObjectDecoder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/qyft/gd/device/client/TcpClient.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/qyft/gd/device/client/TcpClient.java b/src/main/java/com/qyft/gd/device/client/TcpClient.java index 078382f..92e8ce4 100644 --- a/src/main/java/com/qyft/gd/device/client/TcpClient.java +++ b/src/main/java/com/qyft/gd/device/client/TcpClient.java @@ -11,6 +11,7 @@ import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.json.JsonObjectDecoder; import io.netty.util.CharsetUtil; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; @@ -55,6 +56,7 @@ public class TcpClient { .handler(new ChannelInitializer<>() { @Override protected void initChannel(Channel ch) { + ch.pipeline().addLast(new JsonObjectDecoder()); ch.pipeline().addLast(deviceMessageHandler); ch.pipeline().addLast(new TcpConnectionHandler()); } @@ -93,8 +95,9 @@ public class TcpClient { try { channel.writeAndFlush(byteBuf); return true; - } finally { - byteBuf.release(); // 确保释放资源 + } catch (Exception e) { + log.error("TCP发送请求失败: {}", request, e); + return false; } } else { log.error("TCP服务未连接,无法发送请求: {}", request); @@ -122,8 +125,10 @@ public class TcpClient { CompletableFuture future = new CompletableFuture<>(); deviceMessageHandler.responseMap.put(request.getId(), future); try { - log.info("发送TCP指令(同步) {}", JSONUtil.toJsonStr(request)); - if (this.send(JSONUtil.toJsonStr(request))) { + request.getParams().put("class", "test"); + String requestJsonStr = JSONUtil.toJsonStr(request); + log.info("发送TCP指令(同步) {}", requestJsonStr); + if (this.send(requestJsonStr)) { return future.get(tcpConfig.getFeedbackTimeout(), TimeUnit.MILLISECONDS); // 等待 FEEDBACK 响应 } else { return null;