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

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

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

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

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();

[size=medium]

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

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');


[size=medium]

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

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();


[size=medium]全部代码参见我的git:[url]https://github.com/wylazy/tornado-chat[/url][/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值