赖勇浩的编程私伙局

珠三角技术沙龙发起人之一,呆过网易,目前在一家创业网游公司负责技术。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。twi ...

↑我也要推荐

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

发布时间:2011-08-24 21:35:50, 关注:+14235, 赞美:+5, 不爽:+9

本文标签: orbited rabbitmq

原始出处: Coz.Blog

最近公司要用到服务器推送技术,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, 就可以实时聊天啦。。。

如果你觉得本站对你有帮助,欢迎向本站赞助 :P

使用支付宝捐赠

Copyright© Python4cn(news, jobs) simple-is-better.com, 技术驱动:powered by web.py 空间主机:Webfaction

版权申明:文章转载已注明出处,如有疑问请来信咨询。本站为 python 语言推广公益网站,与 python 官方没有任何关系。

联系/投搞/留言: en.simple.is.better@gmail.com 向本站捐赠