通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
# 6. message\_bus #### 1. 介绍 本来是要先写`ActionCable`的,不过在写`ActionCable`之前,先来写写[message\_bus](https://github.com/SamSaffron/message_bus)。它不是websocket的内容,但它在ActionCable出现之前用得蛮多,以后可能会少用了,但它还是一个优秀的gem。 `message_bus`的机制是轮循,长循环,或者EventSource相关的,它在前后端都进行了整合,很方便使用。如果在以前要自己手动使用轮循机制,可能得手动写一些js代码,然而`message_bus`不仅在js端进行了封装,在后端也提供了一种叫pub/sub的机制,理解了`message_bus`,也能更好的理解`ActionCable`,因为很概念是互通的。 #### 2. 使用 我们还是来实现之前的聊天室来例子,来玩一下message\_bus。 安装。 ``` gem 'message_bus' gem 'puma' ``` 添加app/controllers/chat\_controller.rb文件,内容如下: ``` class ChatController < ApplicationController def chat MessageBus.publish "/channel", params[:text] head 200, content_type: "text/html" end end ``` 主要是`MessageBus.publish "/channel", params[:text]`这一行,表示向`/channel`这个通道推送`params[:text]`参数中的数据。 在config/routes.rb中添加路由。 ``` Rails.application.routes.draw do post "/chat", to: "chat#chat" end ``` 分别添加view和js。 ``` h1 Tubesock Chat pre id="output" = form_tag "/chat", class: "chat", remote: true input placeholder="hello world" autofocus=true name="text" ``` ``` MessageBus.start() MessageBus.callbackInterval = 500 MessageBus.subscribe "/channel", (data) -> $("#output").append "#{data}<br>" ``` `MessageBus.subscribe "/channel"`表示订阅服务器端推送过来的通道的数据,还有,`callbackInterval`表示的是轮循的时间。 最后的效果如下: ![](https://box.kancloud.cn/c3d97d10f1d46343ffbd327aa624fd6c_898x387.png) 本篇完结。 下一篇:[websocket之actioncable入门(七)](http://www.rails365.net/articles/websocket-zhi-actioncable-ru-men-qi)