使用 eventmachine 发送哈希
我想将填充有数据的哈希从 EventMachine 客户端发送到服务器。问题是服务器 receive_date 方法只打印一个字符串。
服务器:
def receive_data(data)
send_data("Ready")
puts data[:total]
end
客户端:
def receive_data(data)
send_data( get_memory() )
end
def get_memory
sigar = Sigar.new
mem = sigar.mem
swap = sigar.swap
memory = { :total => (mem.total / 1024), :cat => "kwiki", :mouse => "squeaky" }
end
这一行: put data[:total]
仅打印 nil
I want to send a hash populated with data from a EventMachine client to a server. The problem is that the server receive_date method just prints a string.
The server:
def receive_data(data)
send_data("Ready")
puts data[:total]
end
The client:
def receive_data(data)
send_data( get_memory() )
end
def get_memory
sigar = Sigar.new
mem = sigar.mem
swap = sigar.swap
memory = { :total => (mem.total / 1024), :cat => "kwiki", :mouse => "squeaky" }
end
This line: puts data[:total]
prints only nil
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不在发送之前将 Hash 转换为 JSON 字符串,并在服务器收到它时将其转换回 Hash?
Why don't you convert the Hash to a JSON string before sending it, and convert it back to a Hash when the server receive it?
您需要序列化通过线路发送的数据。换句话说,通常所有内容都以纯 ascii 格式输出。在您的情况下,您可以使用 YAML 进行序列化,因为您的内存哈希仅包含 ascii 字符。
客户端:
require 'yaml'
服务器:
require 'yaml'
当然还有其他序列化方法,例如 JSON 等。
You need to serialize the data that you send over the wire. In other words, normally everything is outputted as plain ascii. In your case you could use YAML for serialization, since you memory hash only contains ascii chars.
client:
require 'yaml'
server:
require 'yaml'
Of course there are other serialization methods like JSON, or something.
嘿,rtaconni,
如果您想从自定义对象发送数据,您必须做一些不同的事情。您可以将 DRbUndumped 模块包含在您的类中,以使您的类成为可封送的。
您可以构建该模块并将其包含在您的类中。
http://www.ruby-doc.org /stdlib/libdoc/drb/rdoc/classes/DRb/DRbUndumped.html
例如。
现在您可以使用 Marshal.dump(object) 和 Marshal.load(object),只要接收者文件/进程也共享(例如,需要“sigar”),那么它将能够使用您的 Ruby 对象,而无需必须对对象进行昂贵的转换才能来回发送它。
Marshal.load()、Marshal.dump() 几乎适用于所有对象,在某些特殊情况下,套接字会遇到异常。
快乐黑客。
Hey rtaconni,
You have to do things a little different if you want to send the data from a custom object. There is the DRbUndumped module you can include in your class to have your class become Marshalable.
You can build the module and include it with your class.
http://www.ruby-doc.org/stdlib/libdoc/drb/rdoc/classes/DRb/DRbUndumped.html
ex.
Now you can use Marshal.dump(object), and Marshal.load(object), and as long as the recipient file / process also shared (eg. require 'sigar') then it will be able to work with your Ruby object without having to do costly transformations to the Object just to send it back and forth.
Marshal.load(), Marshal.dump() work with almost all Objects, there are some special cases with Sockets where Marshaling runs into exceptions.
Happy Hacking.