返回顶部

收藏

Tornado 实现实时消息聊天

更多

关键代码之 MessageServer

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import uuid

unique_id = lambda: str(uuid.uuid1())

class MessageServer(object):
    """消息服务器
    @param id: 服务器标识, 默认为 UUID
    """
    servers = {}

    def __init__(self, id=None):
        self.id = id or unique_id()
        self.observers = []
        self.messages = []
        self.__class__.servers[id] = self

    def listen(self, success_callback):
        self.observers.append(success_callback)
        return success_callback

    def add_message(self, message, id=None):
        id = id or unique_id()
        try:
            self.messages.append((id,message))
            [callback(id, message) for callback in self.observers]
        finally:
            self.observers = []

异步 Controller

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import web
import message
import json

msgsrv = message.MessageServer()
json_encode = json.JSONEncoder().encode

class ChatMessageController(web.Controller):
    @web.asynchronous
    def get(self):
        @msgsrv.listen
        def observer(id, msg):
            update_msg = json_encode({'id':id,'msg':msg})
            try:
                self.finish(update_msg)
            except IOError:
                pass

    def post(self):
        name = unicode(self.get_argument("username")).strip()
        content = unicode(self.get_argument("content")).strip()
        msgsrv.add_message("%s: %s" % (name,content))

标签:Tornado,jQuery,Python,精华

收藏

0人收藏

支持

0

反对

0