Python 的服务器推送解决方案:Orbited + RabbitMQ

出处: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, 就可以实时聊天啦。。。

你可能感兴趣的:(Python 的服务器推送解决方案:Orbited + RabbitMQ)