2009-11-16 58 views
4

我想通过TCP在Ruby进程之间发送消息,而不使用可能限制潜在消息内容的结束字符。这排除了天真的socket.puts/gets方法。 标准库中是否有基本的TCP消息实现?我想避免Drb保持一切简单。)一个简单的TCP消息协议?

回答

6

似乎没有规范的,可重用的解决方案。

因此,这里是为档案的基本实现:

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) 
1

在这种情况下发送字符串的常用方法是发送一个整数(但是你喜欢编码)的字符串的大小,然后是那么多字节。您可以节省空间,但仍然允许使用类似UTF-8的计划的任意大小。

+2

是的,我知道,我不知道是否有实现这种网络协议规范库。 – 2009-11-16 18:02:38