|
@ -11,6 +11,7 @@ import io.netty.buffer.Unpooled; |
|
|
import io.netty.channel.*; |
|
|
import io.netty.channel.*; |
|
|
import io.netty.channel.nio.NioEventLoopGroup; |
|
|
import io.netty.channel.nio.NioEventLoopGroup; |
|
|
import io.netty.channel.socket.nio.NioSocketChannel; |
|
|
import io.netty.channel.socket.nio.NioSocketChannel; |
|
|
|
|
|
import io.netty.handler.codec.json.JsonObjectDecoder; |
|
|
import io.netty.util.CharsetUtil; |
|
|
import io.netty.util.CharsetUtil; |
|
|
import jakarta.annotation.PostConstruct; |
|
|
import jakarta.annotation.PostConstruct; |
|
|
import lombok.RequiredArgsConstructor; |
|
|
import lombok.RequiredArgsConstructor; |
|
@ -55,6 +56,7 @@ public class TcpClient { |
|
|
.handler(new ChannelInitializer<>() { |
|
|
.handler(new ChannelInitializer<>() { |
|
|
@Override |
|
|
@Override |
|
|
protected void initChannel(Channel ch) { |
|
|
protected void initChannel(Channel ch) { |
|
|
|
|
|
ch.pipeline().addLast(new JsonObjectDecoder()); |
|
|
ch.pipeline().addLast(deviceMessageHandler); |
|
|
ch.pipeline().addLast(deviceMessageHandler); |
|
|
ch.pipeline().addLast(new TcpConnectionHandler()); |
|
|
ch.pipeline().addLast(new TcpConnectionHandler()); |
|
|
} |
|
|
} |
|
@ -93,8 +95,9 @@ public class TcpClient { |
|
|
try { |
|
|
try { |
|
|
channel.writeAndFlush(byteBuf); |
|
|
channel.writeAndFlush(byteBuf); |
|
|
return true; |
|
|
return true; |
|
|
} finally { |
|
|
|
|
|
byteBuf.release(); // 确保释放资源 |
|
|
|
|
|
|
|
|
} catch (Exception e) { |
|
|
|
|
|
log.error("TCP发送请求失败: {}", request, e); |
|
|
|
|
|
return false; |
|
|
} |
|
|
} |
|
|
} else { |
|
|
} else { |
|
|
log.error("TCP服务未连接,无法发送请求: {}", request); |
|
|
log.error("TCP服务未连接,无法发送请求: {}", request); |
|
@ -122,8 +125,10 @@ public class TcpClient { |
|
|
CompletableFuture<DeviceFeedback> future = new CompletableFuture<>(); |
|
|
CompletableFuture<DeviceFeedback> future = new CompletableFuture<>(); |
|
|
deviceMessageHandler.responseMap.put(request.getId(), future); |
|
|
deviceMessageHandler.responseMap.put(request.getId(), future); |
|
|
try { |
|
|
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 响应 |
|
|
return future.get(tcpConfig.getFeedbackTimeout(), TimeUnit.MILLISECONDS); // 等待 FEEDBACK 响应 |
|
|
} else { |
|
|
} else { |
|
|
return null; |
|
|
return null; |
|
|