Browse Source

fix:TCP通信增加JsonObjectDecoder

master
白凤吉 5 months ago
parent
commit
b73493029d
  1. 13
      src/main/java/com/qyft/gd/device/client/TcpClient.java

13
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<DeviceFeedback> 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;

Loading…
Cancel
Save