有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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客户端发送的消息时,我看不到相同的字节数组。 比如说,如果我发送字节[]字节数组=新字节[]{(字节)0x06,(字节)0x12};。在服务器中,当它被接收时,它是:[84,-19,0,5,117,114,0,2,91,66,-84,-13,23,-8,6,8,84,-32,2,0,0,0,120,112,0,0,0,0,2,6,18]

我试图在服务器端接收相同的字节数组。从客户端发送字节数组时,我是否做错了什么。请告知


共 (2) 个答案

  1. # 1 楼答案

    我尝试使用TCPClient发送字节数组,而不是套接字输出流。它成功了

    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服务器。:)

  2. # 2 楼答案

    阿比纳亚

    你的问题是你正在发送一个Object,一个Array是一个对象,你可以在这个link上看到writeObject序列化数组,并将其从客户端发送到服务器,服务器会收到表示该数组的所有字节,这些字节不是您所期望的信息,您只期望数组值

    不应该使用writeObject(Object obj),而应该使用write(byte[] buf),它发送数组的字节