Python 的伺服器推送解決方案:Orbited + RabbitMQ

來源:互聯網
上載者:User
出處:http://simple-is-better.com/

最近公司要用到伺服器推送技術,google了一下,nodejs固然好,但是公司的東西都是python搞的,

所以選擇了python的 Orbited +  RabbitMQ,無奈Orbited文檔極其缺乏,所以要做下筆記。

以下都是在windows平台上搞的測試。原理:

Orbited的安裝:

pip install Twisted Orbited stomp.py

RabbitMQ:先要裝好Erlang,然後下RabbitMQ的win版exe檔案安裝,由於要用到stomp協議,

所以要下兩個外掛程式amqp_client-2.5.1.ez,rabbitmq_stomp-2.5.1.ez,

丟到rabbitmq\plugins目錄下,然後在C:\Documents and Settings\CZ.Chen\Application Data\RabbitMQ放一個rabbitmq.config,內容為

[
  {rabbitmq_stomp, [{tcp_listeners, [{"127.0.0.1", 61613}]}]}
].

然後啟用這兩個外掛程式,啟動RabbitMQ服務。

下面回到python,架構用了TG2,我已經建了個叫comet的項目,在comet下放一個chat.ini,來配置Orbited

[listen]
# this is the server which provides the socket-proxy for javascript

http://:9000

# the following enables the MorbidQ STOMP Message Queue
#stomp://:61613

[access]
# allow incoming HTTP requests on port 9000 to connect to
# localhost:61613 (i.e. the MorbidQ STOMP server)
# The * refers to the
#* -> localhost:61613
* -> localhost:61613

[global]
session.ping_interval = 300

然後在controllers\root.py加入代碼,我省略了一些代碼,代碼如下:

# -*- coding: utf-8 -*-
"""Main Controller"""
from tg import expose, flash, require, url, request, redirect, response
from pylons.i18n import ugettext as _, lazy_ugettext as l_
from tgext.admin.tgadminconfig import TGAdminConfig
from tgext.admin.controller import AdminController
from repoze.what import predicates

from comet.lib.base import BaseController
from comet.model import DBSession, metadata
from comet import model
from comet.controllers.secure import SecureController

from comet.controllers.error import ErrorController

import stomp
import json

###rabbitmq
conn = stomp.Connection([('0.0.0.0', 61613), ('127.0.0.1', 61613)], 'guest', 'guest')
print conn
conn.start()
conn.connect(wait=True)
conn.subscribe(destination='/topic/rfid', ack='auto')
###########
__all__ = ['RootController']

class RootController(BaseController):
     
    @expose('comet.templates.chat')
    def chat(self):
        """Handle the front-page."""
        return {}
   
    @expose('json')
    def add_msg(self, **kw):
        print kw
        conn.send(
            json.dumps({'msg': kw.get('msg', '')}),   
            destination='/topic/rfid')
        return {}

其中要把orbited包下的static目錄copy一份改名為orbited,放到comet項目的comet\public目錄下,

然後在templates再增加一個template:chat.mak, 代碼如下:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/orbited/JSON.js"></script>
<script type="text/javascript" src="/orbited/Orbited.js"></script>
<script type="text/javascript">
    // This line is required to allow our chat server and this
    // page to operate on different ports...
    document.domain = document.domain;
    // Establish the port and server for the Orbited server
    Orbited.settings.port = 9000;
    Orbited.settings.hostname = "127.0.0.1";
   
    Orbited.loggers['Orbited.TCPSocket'].enabled = true;
    Orbited.settings.log = true
    // Enable streaming operation
    Orbited.settings.streaming = true;
    // This object is referenced by stomp.js
    TCPSocket = Orbited.TCPSocket;
</script>
<script type="text/javascript" src="/orbited/protocols/stomp/stomp.js"></script>
<script type="text/javascript">
    var add_message = function( text ) {
        var node = $('<div class="chat-message"></div>');
        node.append( text['msg'] );
        $('.chat-trace').append( node );
    };
    $(document).ready( function() {
        stomp = new STOMPClient();
        stomp.onconnectedframe = function(frame) {
            stomp.subscribe( "/topic/rfid" );
        };
        stomp.onmessageframe = function( frame ) {
            add_message( JSON.parse(frame.body) );
            //add_message( frame.body );
        };
        stomp.connect('localhost', 61613, 'guest', 'guest');
        $('.chat-entry .chat-trigger').click( function() {
            var chatter = $('.chat-entry .chatter');
            var value = chatter.attr( 'value' );
            if (value.length) {
                //stomp.send( value, "/messages" );
                $.post("/add_msg", {"msg": value});
                chatter.attr( 'value', '' );
            }
        });
    });
</script>

  <div id="chat">
    <h2>Real-time Chat</h2>
    <div class="chat-trace">
    </div>
    <div class="chat-entry">
        Chat:
        <input class="chatter" />
        <button class="chat-trigger">Send</button>
    </div>
  </div>

然後切換到comet項目的目錄下,運行orbited --config=chat.ini,啟動orbited, 

然後再運行paster serve --reload development.ini啟動TG2,

然後瀏覽器開啟兩個頁面:http://127.0.0.1:8080/chat, 就可以即時聊天啦。。。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.