问题描述
我正在 Ruby on Rails 上使用 Jabber 编写聊天应用程序.发送消息很容易实现,但循环接收消息是一个很大的挑战.
I am writing a chat application, using Jabber, on Ruby on Rails. Sending messages was quite easy to implement, but receiving messages in a loop is quite a challenge.
我想在不刷新浏览器的情况下从服务器获取回调.为此,我尝试使用 ActionController::Live.
I want to get callbacks from the server without browser refreshes. I tried to use ActionController::Live for this.
在我的客户端,我的代码是:
In my client side, my code is:
var source = new EventSource('/chat/events');
source.addEventListener('refresh', function(event)
{
AddMessage(event.data);
});
我的控制器代码是:
def chat_events
# SSE expects the `text/event-stream` content type
response.headers['Content-Type'] = 'text/event-stream'
sse = Reloader::SSE.new(response.stream)
puts "Starting XMMP call"
begin
@xmmpClient = XmppClient.new
@xmmpClient.loginUsingNameAndPassword(****, ***)
@xmmpClient.listen_connections sse
rescue IOError
puts "Error"
# When the client disconnects, we'll get an IOError on write
ensure
puts "closing stream"
sse.close
end
end
而且,我的 XMMP 客户端是:
And, my XMMP client is:
def listen_connections(writer = nil)
if not @logged_in
puts "Not logged"
raise "Not logged"
end
@robot.send(Jabber::Presence.new.set_show(nil))
loop do
puts "Listening callback"
@robot.add_message_callback do |message|
puts "Got message " + message.inspect
if not writer.nil?
writer.write({ :message => message.body }, :event => 'refresh')
end
end
sleep 2
end
end
我得到了什么:
- 控制器的
chat_events
方法大约每秒调用一次. - 因此,一次执行多个回调.
当我收到一条消息时,我收到了四五次.
- The
chat_events
method of the controller is called every second or so. - Because of this, several callbacks are executed at once.
When I got a message, I got it four or five times.
{"message":"fffdsfd"}
{"message":"fffdsfd"}
{"message":"fffdsfd"}
{"message":"fffdsfd"}
最糟糕的是 - 我的服务器没有响应其他响应,尽管我使用 Puma 多线程服务器.
And the worst stuff - my server is not responding to other responses, although I use the Puma multi-threaded server.
实现此类功能的正确方法是什么?
What is the correct way to implement functionality like this?
推荐答案
我得到解决方案
puts "."
client.add_message_callback do |message|
if message.type != :error
arr = message.from.to_s.split('@')
puts arr[0]
puts message.body
end
end
while 1
end
这篇关于无限监听 jabber 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!