0
votes

i have a socket server that written by java(using netty),i use LengthFieldBasedFrameDecoder to decode message ; the encoder ,if use java should be:

Message.Type msgType = in.type();
// All messages have the frame length, message type, and message itself.
int headerLength = 8 + msgType.encodedLength() + in.encodedLength();
// long frameLength = headerLength + bodyLength;
ByteBuf header = ctx.alloc().heapBuffer(headerLength);
//header.writeLong(frameLength);
header.writeLong(headerLength);

msgType.encode(header);
in.encode(header);

but now i need a socket client written by python ,so how do i write the message length(8 bytes,long type) into buffer

2
Did you try ByteBuffer.toArray()? - Evgeniy Dorofeev

2 Answers

0
votes

You basically need to bit-shift stuff. I am not a python programmer so I am not sure about the python syntax but basically this is how its implemented in java:

static void setLong(byte[] memory, int index, long value) {
    memory[index]     = (byte) (value >>> 56);
    memory[index + 1] = (byte) (value >>> 48);
    memory[index + 2] = (byte) (value >>> 40);
    memory[index + 3] = (byte) (value >>> 32);
    memory[index + 4] = (byte) (value >>> 24);
    memory[index + 5] = (byte) (value >>> 16);
    memory[index + 6] = (byte) (value >>> 8);
    memory[index + 7] = (byte) value;
}

So just do the same shifting in python and you should be fine. BTW this is BIG_ENDIAN encoding.

0
votes

A socket client allows you to read byte by byte.

Read 8 bytes, get a byte string:

bytes_sequence = client_socket.read(8)

Note that each element of bytes_sequence is a "character", so you need to use ord() to get its numeric value.

Now convert it into a 8-byte long if you need.

For big-endian data ("network order"), you can

def from_big_endian(bytes_sequence):
  result = 0
  for b in bytes_sequence:
    result = result << 8 + ord(b)  # ord() converts b to integer.
  return result

Or, shorter: reduce(lambda acc, v: (acc << 8) + ord(v), bytes_sequence, 0).

For little-endian sequence, you can e.g. reverse the byte sequence, and handle it as a big-endian sequence:

big_endian_seq = little_endian_seq[::-1]

Or you can write an explicit loop for combining it into an integer like above.