本文介绍了如何从 Rails 控制器推送到 Faye 服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

def 创建message = Message.new(text: params[:message][:text], author: params[:message][:author])如果消息.save渲染json:{结果:'成功'}别的渲染json:{结果:'失败'}结尾结尾

我有客户订阅了 Faye Server:

var subscription = client.subscribe('/foo', function (message) {获取消息();});

我想在创建消息时向 Faye 发布一些消息.如 Faye Ruby Sever 文档中所列,我必须这样做:

需要'eventmachine'EM.run {client = Faye::Client.new('http://localhost:9292/faye')client.subscribe('/foo') 做 |message|puts message.inspect结尾client.publish('/foo', 'text' => 'Hello world')}

但是当我将此代码粘贴到我的 create 方法中时,它使用 EventMachine 阻塞了 rails 线程并且服务器不再工作.

当我在没有 EventMachine 的情况下使用 client.publish 时,出现错误.

如何从服务器发布到 Faye?我知道有像 faye-railsprivate_pub 这样的 gem,但我想弄清楚如何自己做.有没有办法集成EventMachine和Rails?也许我应该在不同的线程上运行 EventMachine?

解决方案

我没有使用 Event Machine 但我在 rails 中使用了 Fay-web Socket,我使用的是 thin web-服务器,以便我的应用程序显示通知.

首先将这一行添加到您中 Gemfile

gem 'faye'宝石薄"

现在!运行 bundle install 命令来安装 gem,它是依赖.

创建一个 faye.ru 文件并添加给定的行(用于运行的机架文件Faye服务器).

需要'rubygems'需要薄"需要'faye'faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)运行 faye_server

现在将行添加到您的 application.erb 文件

<%= javascript_include_tag 'application', "http://localhost:9292/faye.js", 'data-turbolinks-track' =>真%>

创建一个名为 broadcast 或任何名称的方法在 websoket.rb 中适合你(首先创建 websoket.rb 文件config/initializers 内) .

模块 Websocket定义广播(频道,味精)消息 = {:channel =>频道,:数据=>留言}uri = URI.parse("http://localhost:9292/faye")Net::HTTP.post_form(uri, :message => message.to_json)结尾结尾

现在在你的模型或控制器中你想要的地方使用这个方法.

就我而言,我在 **Notification.rb 中使用它来发送通知.**

示例

after_create :send_notificaton定义发送通知broadcast("/users/#{user.id}", {u​​sername: "#{user.full_name }", msg: "您好,您被邀请参加项目--| #{project.name} | 请检查您的邮件"})结尾

订阅者

<脚本>$(函数(){var faye = new Faye.Client('http://localhost:9292/faye');faye.subscribe('/users/', function (data) {$('#websocket').text(data.username + ":" + data.msg);});});

现在!使用终端运行您的 faye.ru 文件

rackup faye.ru -s thin -E prodcution

了解详情Faye websocket

I have this code:

def create
    message = Message.new(text: params[:message][:text], author: params[:message][:author])
    if message.save
      render json: {result: 'success'}
    else
      render json: {result: 'failure'}
    end
  end

I have client subscribed to Faye Server:

var subscription = client.subscribe('/foo', function (message) {
    getMessages();
});

I want to publish some message to Faye when a message is created. As listed in Faye Ruby Sever documentation, I have to do like this:

require 'eventmachine'

EM.run {
  client = Faye::Client.new('http://localhost:9292/faye')

  client.subscribe('/foo') do |message|
    puts message.inspect
  end

  client.publish('/foo', 'text' => 'Hello world')
}

But when I paste this code into my create method, it blocks the rails thread with EventMachine and server doesn't work any more.

When I use client.publish without EventMachine, I get an error.

How can I publish to Faye from server? I know that there are gems like faye-rails or private_pub, but I want to figure out how to do it myself. Is there any way to integrate EventMachine and Rails? Maybe I should run EventMachine on a different thread?

解决方案

I did't use Event Machine but I use Fay-web Socket in rails , I am using thin web-server for my application to show notification.

First you add this line into you Gemfile

gem 'faye'
gem 'thin'
require 'rubygems'
require 'thin'
require 'faye'
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
run faye_server
<%= javascript_include_tag 'application', "http://localhost:9292/faye.js", 'data-turbolinks-track' => true %>
module Websocket
  def broadcast(channel, msg)
    message = {:channel => channel, :data => msg}
    uri = URI.parse("http://localhost:9292/faye")
    Net::HTTP.post_form(uri, :message => message.to_json)
  end
end

In my case I am using this inside the **Notification.rb to sending notification.**

Example

after_create :send_notificaton

def send_notification
    broadcast("/users/#{user.id}", {username: "#{user.full_name }", msg: "Hello you are invited for project--| #{project.name} | please check your mail"})
end

For subscriber

<div id="websocket" style="background-color: #999999;">
</div>
<script>
$(function () {
var faye = new Faye.Client('http://localhost:9292/faye');
        faye.subscribe('/users/<%= current_user.id %>', function (data) {
            $('#websocket').text(data.username + ": " + data.msg);
        });
    });
</script>

Now ! Run your faye.ru file using terminal

rackup faye.ru -s thin -E prodcution

For detailsFaye websocket

这篇关于如何从 Rails 控制器推送到 Faye 服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 16:29