RoR ActionCable

来源:互联网 发布:全民无双 源码 编辑:程序博客网 时间:2024/06/07 15:46

Rails 5推出了一个激动人心的新技术——Action Cable

从此,Rails正式支持了WebSocket。此前也有第三方Rails框架支持WebSocket(例如WebSocket-rails)但是毕竟不是亲儿子,不太好用。

现在我们简单介绍下Action Cable的使用。

1、检查Rails版本,必须是5以上的

2、新建工程hello_action_cable


3、生成一个普通Controller hello_get


4、修改路由,测试http get协议

在hello_action_cable\config\routes.rb里增加路由

Rails.application.routes.draw do  get 'hello_get/do_hello'  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html  root to: 'hello_get#do_hello'end

 启动服务器


访问


6、生成一个Channel hello_link


7、编写服务端hello_action_cable\app\channels\hello_link_channel.rb

class HelloLinkChannel < ApplicationCable::Channel  def subscribed    # stream_from "some_channel"# 指定订阅来自哪些channel的客户端消息# 这里的channel名 同 hello_action_cable\app\channels下定义的代码文件名stream_from "hello_link_channel"  end  def unsubscribed    # Any cleanup needed when channel is unsubscribed  end  def say_hello(msg_from_client)# 通过广播的方式回应所有客户端消息ActionCable.server.broadcast 'hello_link_channel', message: "response from server (to #{msg_from_client['hello_msg']})"  endend
8、编写javascript客户端

hello_action_cable\app\assets\javascripts\cable.js

// Action Cable provides the framework to deal with WebSockets in Rails.// You can generate new channels where WebSocket features live using the rails generate channel command.////= require action_cable//= require_self//= require_tree ./channels(function() {  alert("Hello init")  this.App || (this.App = {});  App.cable = ActionCable.createConsumer();}).call(this);

hello_action_cable\app\assets\javascripts\channels\hello_link.coffee

App.hello_link = App.cable.subscriptions.create "HelloLinkChannel",  connected: ->    # Called when the subscription is ready for use on the server    alert 'Hello connected'  disconnected: ->    # Called when the subscription has been terminated by the server# 收到来自后台的消息    alert 'Hello disconnected'  received: (data) ->    # Called when there's incoming data on the websocket for this channel    alert 'Hello received' + data['message']  say_hello: (hello_word) ->    # 调用后台hello_linkde的say_hello方法,参数是{"hello_msg":"hello_word"}    @perform 'say_hello', hello_msg:hello_word


8、重启服务器并验证





用搜狗浏览器,右键-->审查元素



输入测试JS语句



断开服务器



0 0