我是这个&的完全新手。我做了一个简单的代码,从RabbitMQ获取数据并将其发送到通过websockets连接的客户端。
问题在于:
$ channel = EM :: Channel.new
EM.run do
class App < Sinatra::Base
get '/' do
haml :index
end
end
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws|
ws.onopen {
AMQP.start(:host => "localhost") do |connection|
$channel = AMQP::Channel.new(connection)
exchange = $channel.fanout("slant", :auto_delete => false, :durable => true)
queue = $channel.queue("my-events", :auto_delete => true, :durable => false)
queue.bind(exchange, :routing_key => "").subscribe(:ack => true) do |headers, payload|
ws.send payload.to_s
puts payload
$channel.acknowledge(headers.delivery_tag, false)
end
end
}
ws.onclose { puts "Client disconnected" }
end
App.run!({:port => 3000})
end
客户有JS喜欢:
$(function(){
ws = new WebSocket("ws://localhost:8080");
ws.onmessage = function(evt) {
var msg = json_parse(evt.data);
row = '<tr><td>' + msg.severity + '</td>' + '<td>' + msg.service + '</td>' + '<td>' + msg.description+ '</td>' + '<td>' + msg.server + '</td>'+ '<td>' + msg.source + '</td>' + '<td>' + msg.date + '</td>' + '<td>' + msg.host_address + '</td>' + '<td>' + msg.additional_info + '</td>' + '<td>' + msg.event_type + '</td>' + '</tr>'
if ($('#alerts tbody tr:first').length > 0){
$('#alerts tbody tr:first').before(row);
} else {
$('#alerts tbody')append(row);
}
};
ws.onclose = function() {
ws.send("Leaves the chat");
};
ws.onopen = function() {
ws.send("Join the chat");
};
});
我不确定出了什么问题?看起来我的代码中存在根本性的错误。
答案 0 :(得分:0)
尝试在单独的线程中运行EventMachine和Sinatra应用程序