tags:

views:

135

answers:

2

I want to send messages between Ruby processes via TCP without using ending chars that could restrict the potential message content. That rules out the naïve socket.puts/gets approach. Is there a basic TCP message implementation somewhere in the standard libs?. (I'd like to avoid Drb to keep everything simple.)

+1  A: 

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

Roger Pate
Yes, I know and I wonder if there's a canonical library that implements such a procotol.
Kay Sarraute
+1  A: 

It seems like there is no canonical, reusable solution.

So here's a basic implementation for the 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)
Kay Sarraute