RoR ActionCable

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']})"
  end
end
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语句



断开服务器






关于WebSocket的一个新技术:workman点击打开链接



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值