`
ipjmc
  • 浏览: 702365 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用Tornado和Redis构建简易聊天室

阅读更多
    Tornado是一个异步Python框架,最初由FriendFeed发起并开源,目前由Facebook维护,非常适合实时做Web应用。
    Redis是一个NoSQL数据库,常用于做缓存系统,这里主要用到了它的Pub/Sub功能。即当一个用户发送一条消息时,所有的用户都会收到消息。
    关于什么是Ajax长轮询(Comet)不再介绍

    我是参照the5fire的一篇博客来组织项目源码的:http://www.the5fire.com/tornado-mvc-helloworld-2.html

    当Tornado收到浏览器的消息时,将这条消息publish到Redis里,所有的subscriber就都会收到通知。

  def post(self) : #接受POST请求
    name = self.get_secure_cookie('name')
    msg = self.get_argument('msg', '') 

    if name == '': 
      name = 'Anonymous'

    data=json_encode({'name':name, 'msg':msg})
    c.publish('test_channel', data) #收到将消息publish到Redis
    self.write(json_encode({'result':True}));
    self.finish();



    将Tornado超时时间设置为60s,如果在60s内,收到了Redis的消息,就把消息发送给浏览器;如果60s超时了,则发送一条msg为空的消息给浏览器。

import time
import tornado.web
import tornado.gen
import tornadoredis
from tornado.escape import json_encode
from model.entity import Entity

class LongPollingHandler(tornado.web.RequestHandler):

  def initialize(self):
    self.client = tornadoredis.Client()
    self.client.connect() #连接到Redis

  @tornado.web.asynchronous
  def get(self):
    self.get_data()

  @tornado.web.asynchronous
  def post(self):
    self.get_data()
  
  @tornado.gen.engine
  def subscribe(self): #订阅Redis的消息
    yield tornado.gen.Task(self.client.subscribe, 'test_channel')
    self.client.listen(self.on_message)

  
  def get_data(self):
    if self.request.connection.stream.closed():
      return
       
    self.subscribe()

    num = 60 #设置超时时间为60s
    tornado.ioloop.IOLoop.instance().add_timeout(
      time.time()+num,
      lambda: self.on_timeout(num)
    )


  def on_timeout(self, num):
    self.send_data(json_encode({'name':'', 'msg':''}))
    if (self.client.connection.connected()):
      self.client.disconnect()

  def send_data(self, data): #发送响应
    if self.request.connection.stream.closed():
      return

    self.set_header('Content-Type', 'application/json; charset=UTF-8')
    self.write(data)
    self.finish()

 
  def on_message(self, msg): #收到了Redis的消息
    if (msg.kind == 'message'):
      self.send_data(str(msg.body))
    elif (msg.kind == 'unsubscribe'):
      self.client.disconnect()

  def on_finish(self):
    if (self.client.subscribed):
      self.client.unsubscribe('test_channel');


   

    浏览器JavaScript代码如下,每当服务器返回结果以后,就立即再发送一个请求到服务器。因为空闲的时候,服务器要等60s才会有响应,所以这并不会消耗很多资源。

      var updater = {
        poll: function(){
          $.ajax({url: "/longpolling",
            type: "POST",
            dataType: "json",
            success: updater.onSuccess,
            error: updater.onError});
        },
        onSuccess: function(data, dataStatus){
          try{
            if (data.msg != "") {
              $("p").append(data.name+": " + data.msg + "<br />");
            }
          }
          catch(e){
            updater.onError(e);
            return;
          }
          updater.poll();  //收到响应后立即再发一条请求
        },
        onError: function(e){
          if (e.message)
            console.log("Poll Error" + e.message);
          else
            console.log(e);
        }
      };
  
      updater.poll();


全部代码参见我的git:https://github.com/wylazy/tornado-chat
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics