Problem with tcp socket write not working

60 Views Asked by At

I'm trying to write a message created using protobuf to a client socket, but I don't know why only the code below works.

   mClientSSLSocket.getOutputStream().write(intToByte(message.getSerializedSize()));
   message.writeTo(mClientSSLSocket.getOutputStream());
  public int getSerializedSize() {
    if (memoizedSerializedSize == -1) {
      memoizedSerializedSize = Protobuf.getInstance().schemaFor(this).getSerializedSize(this);
    }
    return memoizedSerializedSize;
  }
    public static byte[] intToByte(int value) {
        return new byte[] {
            (byte) (value >> 24),
            (byte) (value >> 16),
            (byte) (value >> 8),
            (byte) value };
    }

However:

mClientSSLSocket.getOutputStream().write(message.getSerializedSize()); <--- NOT WORK
mClientSSLSocket.getOutputStream().write(message.toByteArray()); <----- NOT WORK

What I don't understand even more is that the above code only works on Android <-> Android

  • and does NOT work on Android <-> IOS.

Well, I suspect that the reason it doesn't work on Android <-> IOS is because of the line separator... How can I use the line separator in an object type other than a String type?

Can anyone explain the above?

mClientSSLSocket.getOutputStream().write(message.getSerializedSize()); <--- NOT WORK
mClientSSLSocket.getOutputStream().write(message.toByteArray()); <----- NOT WORK
1

There are 1 best solutions below

2
Marc Gravell On

As @user207421 notes, OutputStream.write(int) only writes a single byte:

The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

You always want to write 4 bytes, hence why this isn't working.