Simple TCP Messaging Protocol?

I want to send messages between Ruby processes over TCP without the use of trailing characters, which could limit the potential content of the message. This eliminates the naive socket.puts / gets approach. Is there a basic implementation of TCP messages somewhere in standard libraries ?. (I would like to avoid Drb so that everything is simple.)

+4
source share
2 answers

There seems to be no canonical, reusable solution.

So, here is the basic implementation for archives:

module Messaging # Assumes 'msg' is single-byte encoded # and not larger than 4,3 GB ((2**(4*8)-1) bytes) def dispatch(msg) write([msg.length].pack('N') + msg) end def receive if (message_size = read(4)) # sizeof (N) message_size = message_size.unpack('N')[0] read(message_size) end end end # usage message_hub = TCPSocket.new('localhost', 1234).extend(Messaging) 
+6
source

The usual way to send strings in this situation is to send an integer (encoded as you like) for the size of the string followed by this many bytes. You can save space, but still allow arbitrary sizes using the UTF-8- like scheme for this integer.

+1
source

All Articles