rails4使用长连接

开发瑞信通的时候偶然看到了ActionController::Live,可以做类似即时通讯的东西,不过不支持webrick,只支持puma和unicorn~,具体使用如下:

class MyController < ActionController::Base
# 步骤 1
include ActionController::Live
def stream
# 步骤 2
response.headers['Content-Type'] = 'text/event-stream'
100.times {
# 步骤 3 直接使用 response.stream
response.stream.write "hello world\n"
sleep 1
}
ensure
# 步骤 4
response.stream.close
end
end

可以直接在页面直接访问 /my/stream即可
不过更合适通过ajax去访问,因为HTML5有一个服务器推送事件(Server-sent Events)
http://www.ibm.com/developerworks/cn/web/1307_chengfu_serversentevent/
通过ajax访问如下:

jQuery(document).ready(function(){
var source = new EventSource("/my/stream");
source.addEventListener('update', function(e){
$("#target_div").append(e)
// update a div, reload a section of the page
});
// you can add different event listeners to
// process some logic based on the event push
// from the server to do something unique based
// users leaving, joining the application or other
// kinds of events not releated to users.
});

下面有个ActionController::Live +redis+resque的简单实时聊天实现,有兴趣的同学可以去看看
http://stackoverflow.com/questions/29150274/how-to-use-actioncontrollerlive-along-with-resque-redis-for-chat-applicatio

你可能感兴趣的:(rails4使用长连接)