Ruby on Rails - Faye Framework - private_pub

时间:2013-04-29 14:49:59

标签: ruby-on-rails chat publish-subscribe faye

我正在使用private_pub来实现一对一的聊天式应用程序。

以下是我的故事:作为用户,我想在合作伙伴离开聊天时收到消息 - 关闭窗口等。

在此处查看Faye Monitoring docs是我尝试绑定unsubscribe


# Run with: rackup private_pub.ru -s thin -E production
require "bundler/setup"
require "yaml"
require "faye"
require "private_pub"
require "active_support/core_ext"

Faye::WebSocket.load_adapter('thin')

PrivatePub.load_config(File.expand_path("../config/private_pub.yml", __FILE__),     ENV["RAILS_ENV"] || "development")

wts_pubsub = PrivatePub.faye_app

wts_pubsub.bind(:subscribe) do |client_id, channel|
puts "[#{Time.now}] Client #{client_id} joined  #{channel}"
end

wts_pubsub.bind(:unsubscribe) do |client_id, channel|
  puts "[#{Time.now}] Client #{client_id} disconnected from #{channel}"
  PrivatePub.publish_to channel, { marius_says: 'quitter' }
end

run wts_pubsub

但我不断收到超时:[ERROR] [Faye::RackAdapter] Timeout::Error

进入PrivatePub#publish_to时,数据保存了我从Rails或private_pub应用程序发布时的预期,但private_pub应用程序一直悬挂。

如何从private_pub发布工作?

2 个答案:

答案 0 :(得分:0)

您的第二次绑定应该是disconnect事件,而不是unsubscribe

另外,请记住在浏览器窗口关闭时在客户端代码中触发Faye / PrivatePub disconnect事件。

注意:您可能需要对所有与Faye服务器的开放会话执行此操作,或者仅根据聊天应用程序的设计逐个通道执行此操作

在普通JS中,这可能类似于:

window.onbeforeunload = functionThatTriggersFayeDisconnectEvent;

很抱歉没有使用正确的标记,从手机发布。

答案 1 :(得分:0)

经过数小时的研究和多次尝试,这是我找到的解决方案:

PrivatePub.publish_to channel, { marius_says: 'quitter' }替换为:

system "curl http://localhost:9292/faye -d 'message={\"channel\":\"#{channel}\", \"data\":{\"channel\":\"#{channel}\",\"data\":{\"message\":{\"content\":\"#{client_id} disconnected from this channel.\"}}}, \"ext\":{\"private_pub_token\":\"ADD_APPROPRIATE_SECRET_HERE\"}}' &"

这将触发异步请求(curl +&),它将绕过问题。不是最好的解决方案,但它确实有效。