Question

I'm trying to send something via socket so I made a simple protocol which is :

[Message length (uint32)][Packet id(uint32)][Message]

So, how can I send a message with this protocol ? I tried this :

message = 'hi'
parent_socket.send([message.length, 2].pack('LL') + message, 0)

and it doesn't seems to work. What I get is just the length and the packet id. How can I figure this out?

(Updated) The code I'm using to receive the message is :

if child_socket.ready?
  header = child_socket.read(8).unpack('LL')
  length = header[0]
  packet = header[1]
  case packet
    when 1
      stdin.write(child_socket.read(length))
    when 2
      puts child_socket.read(length)
      #send console
    else
      Console.show "Unknown packet : #{packet}"
end

The output is 10. Seems normal (4 + 4 + 2)

in that case, length is 2 and packet is 2. So it switch to 'when 2' but it output nothing.

Was it helpful?

Solution

The problem is you are only reading the first 8 byes.

header = child_socket.read(8).unpack('LL')

According to the docs for IO#read, if you don't pass a length, it will read to EOF, which should get everything. So just remove that length parameter:

header = child_socket.read.unpack('LL')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top