美文网首页
rails4使用长连接

rails4使用长连接

作者: 夏_至 | 来源:发表于2016-05-26 23:54 被阅读241次

    开发瑞信通的时候偶然看到了ActionController::Live,可以做类似即时通讯的东西,不过不支持webrick,只支持puma和unicorn~,具体使用如下:
    <pre>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
    </pre>
    可以直接在页面直接访问 /my/stream即可
    不过更合适通过ajax去访问,因为HTML5有一个服务器推送事件(Server-sent Events)
    http://www.ibm.com/developerworks/cn/web/1307_chengfu_serversentevent/
    通过ajax访问如下:
    <pre>
    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.
    });
    </pre>

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

    相关文章

      网友评论

          本文标题:rails4使用长连接

          本文链接:https://www.haomeiwen.com/subject/cltekttx.html