Sending a hash using eventmachine
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.开发者_如何学JAVA
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
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?
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'
def receive_data(data)
send_data(get_memory().to_yaml)
end
server:
require 'yaml'
def receive_data(data)
puts YAML.load(data)
end
Of course there are other serialization methods like JSON, or something.
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.
require 'drb'
include DRbUndumped
class Sigar
def initialize(*args)
end
def ect
end
end
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.
精彩评论