先决条件:
- 红宝石 2.0.0+
- 导轨 4.0.0+
- Redis
- Puma
初始化器:
创建一个redis.rb
初始化程序文件在config/initializers
目录,全球化实例redis
。建立一个heartbeat
线程(5 秒到 5 分钟之间的任何时间都可以,具体取决于您的要求):
$redis = Redis.new
heartbeat_thread = Thread.new do
while true
$redis.publish("heartbeat","thump")
sleep 15.seconds
end
end
at_exit do
heartbeat_thread.kill
$redis.quit
end
控制器:
您需要将两个方法添加到您的ChatController
, pub
and sub
。的作用pub
是将聊天事件和消息发布到redis
, and sub
订阅这些事件。它应该看起来像这样:
class ChatController < ApplicationController
include ActionController::Live
skip_before_filter :verify_authenticity_token
def index
end
def pub
$redis.publish 'chat_event', params[:chat_data].to_json
render json: {}, status: 200
end
def sub
response.headers["Content-Type"] = "text/event-stream"
redis = Redis.new
redis.subscribe(['chat_event', 'heartbeat']) do |on|
on.message do |event, data|
response.stream.write "event: #{event}\ndata: #{data}\n\n"
end
end
rescue IOError
logger.info "Stream Closed"
ensure
redis.quit
response.stream.close
end
end
In your routes
, make pub a POST
and sub a GET
,并将路径与类似的东西相匹配/chat/publish
and /chat/subscribe
.
咖啡脚本/Javascript:
假设您的聊天应用程序的实际网页位于/chat
,你需要写一些JavaScript实际发送和接收聊天消息。
为了便于理解,我们假设您的网页只有一个文本框和一个按钮。点击按钮应该将文本框的内容发布到聊天流,我们可以使用 AJAX 来做到这一点:
$('button#send').click (e) ->
e.preventDefault()
$.ajax '/chat/publish',
type: 'POST'
data:
chat_data: {
message: $("input#message").val()
timestamp: $.now()
error: (jqXHR, textStatus, errorThrown) ->
console.log "Failed: " + textStatus
success: (data, textStatus, jqXHR) ->
console.log "Success: " + textStatus
现在,您还需要能够订阅和接收聊天消息。你需要使用EventSource
为了这。使用事件源,为 SSE 打开一个通道,以便您可以接收事件,并使用该数据来更新视图。在此示例中,我们仅将它们记录到 javascript 控制台。
代码应该如下所示:
$(document).ready ->
source = new EventSource('/chat/subscribe')
source.addEventListener 'chat_event', (e) ->
console.log(e.data)
Note: 将上面的两个代码块放在您的controllername.coffee
文件,对于本例来说应该是chat.js.coffee
在你的app/assets/javascript
目录。您还需要确保它已加载到资产管道中。require
它在你的application.js
文件(如果您还没有调用require tree .
).
启用并行请求:
在您的开发环境中,您必须通过将这两行添加到您的config/environments/development.rb
:
config.preload_frameworks = true
config.allow_concurrency = true
现在启动浏览器,浏览到/chat
并见证魔法。当您键入消息并单击按钮时,该网页的所有实例都会收到该消息。
这就是你如何制作一个基本的聊天应用程序rails
using ActionController::Live
and Redis
。根据您的要求,最终的代码显然会非常不同,但这应该可以帮助您入门。
您应该查看更多资源:
- 温柔的做爱 -是直播吗? http://tenderlovemaking.com/2012/07/30/is-it-live.html
- 铁路广播 -#401 - ActionController::Live http://railscasts.com/episodes/401-actioncontroller-live
- 站点点 -与 Rails 和 SSE 的迷你聊天 http://www.sitepoint.com/mini-chat-rails-server-sent-events/
- GitHub -mohanraj-ramanujam / 直播 https://github.com/mohanraj-ramanujam/live-stream
- 思想机器人 -使用 SSE 的聊天示例 https://robots.thoughtbot.com/chat-example-app-using-server-sent-events