简体   繁体   中英

TCP Client Server communication - The input byte array is modified as the server receives

TCP Server:

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 Client:

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";
}

When the server receives the message sent by TCP Client, I dont see the same byte array. Say, if I send byte[] byteArray = new byte[]{(byte) 0x06, (byte) 0x12};. In Server, when it received, it is : [-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]

I was trying to receive the same byte array in the server side. Am I doing anything wrong while sending the byte array from client. Please advise

I tried with TCPClient to send byte array rather than Socket output stream. And it worked.

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();

This sends the exact byte array to TCP Server. :)

Abinaya

Your problem is that you are sending an Object , an Array is an object as you can see on this link . writeObject serializes the array and sent it from your client to your server and your server receive all the bytes which represents the array which is not the information that you are expecting, you are expecting only the array values.

Instead of using writeObject(Object obj) you should use write(byte[] buf) , which send the byte of an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM