Ruby代码
require 'json'
require 'active_support/gzip'
require 'zlib'
require 'websocket-eventmachine-server'
h ={aaa: 'bbb' , ccc: 'ddd'}
string = JSON(h)
gzip_string = Zlib::Deflate.deflate(string)
EventMachine.run do
WebSocket::EventMachine::Server.start(:host => "0.0.0.0", :port => 9999) do |ws|
ws.onopen do
puts "Client connected"
end
ws.onmessage do |msg, type|
ws.send gzip_string , :type => :binary
end
ws.onclose do
puts "Client disconnected"
end
end
end
var ws = new WebSocket('ws://localhost:9999')
ws.onopen = function(){
ws.send('111'))
}
ws.onmessage = function(e) {
var blob = e.data;
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onload = function (evt) {
var data = pako.inflate(evt.target.result, { to: 'string' })
console.log(JSON.parse(data))
};
}