首页 > 解决方案 > 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]

我试图在服务器端接收相同的字节数组。从客户端发送字节数组时我做错了什么吗?请指教

标签: javatcpreactor-netty

解决方案


我尝试使用 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 服务器。:)


推荐阅读