java - TCP 客户端服务器通信 - 输入字节数组在服务器接收时被修改
问题描述
TCP 服务器:
public Flux<Void> handleMessage(NettyInbound inbound, NettyOutbound outbound, boolean isSBD) {
LOGGER.debug(LOGGER_HANDLE_MESSAGE);
return inbound.receive().asByteArray().flatMap(bytes -> {
LOGGER.info(LOGGER_MESSAGE_RECEIVED);
LOGGER.debug(LOGGER_PAYLOAD, bytes);
});
}
TCP客户端:
byte[] byteArray = new byte[]{(byte) 0x01, (byte) 0x12};
try (Socket socket = new Socket(host, port)) {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject(byteArray);
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
return objectInputStream.readObject();
} catch (Exception ex) {
LOGGER.error("exception occurred" + ex.getMessage());
ex.printStackTrace();
return "Exception";
}
当服务器接收到 TCP Client 发送的消息时,我没有看到相同的字节数组。比如说,如果我发送 byte[] byteArray = new byte[]{(byte) 0x06, (byte) 0x12};。在服务器中,当它收到时,它是:[-84, -19, 0, 5, 117, 114, 0, 2, 91, 66, -84, -13, 23, -8, 6, 8, 84, -32、2、0、0、120、112、0、0、0、2、6、18]
我试图在服务器端接收相同的字节数组。从客户端发送字节数组时我做错了什么吗?请指教
解决方案
我尝试使用 TCPClient 发送字节数组而不是 Socket 输出流。它奏效了。
TcpClient.create()
.host(host)
.port(port)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.wiretap(true)
.connect()
.flatMap(connection ->
connection.outbound().sendByteArray(Mono.just(byteArray))
.then(connection.inbound().receive().asByteArray().next().flatMap(bytes -> {
LOGGER.info("bytes {}", bytes);
return Mono.empty();
}))
.then()
)
.subscribe();
这会将确切的字节数组发送到 TCP 服务器。:)
推荐阅读
- python - django修改数据库对象
- javascript - React JS:FirebaseUI 身份验证持久性适用于 Firefox Mobile 而不是 Chrome Mobile
- laravel-5.4 - 如何在 laravel 5.4 中只在自己的城市看到专家
- json - 如何将 servlet 请求转换为 JSON 请求
- android - 仅从一个片段中不显示片段
- ios - iOS 目标 C 完成块不会在 Azure 移动应用程序框架方法需要的地方返回数据。构建捆绑应用程序
- apache - 在 Hybris 中设置 mod_jk 重定向
- wordpress - 在 wordpress 中添加新页面时无法选择作品集类别
- vba - 将图像对象转换为形状 vba
- javascript - 使用 switch 中的每个函数填充 jQuery 对象