為了加深對tornado的理解,寫了一個tornado chat server, 基於tornado tcpserver,

server的主要作是接收client發送的msg,並把所接收到的msg broadcast到所有的client

#!/usr/bin/env python

from tornado.netutil import TCPServer
from tornado.ioloop  import IOLoop

class Connection(object):
    _conns = set()
    def __init__(self, stream, address):
        Connection._conns.add(self)
        self._stream = stream
        self._address = address
        self._stream.set_close_callback(self.on_close)
        self.read_message()
        print address, "A new user has entered the chat room."
    
    def read_message(self):
        self._stream.read_until('\n', self.broadcast_messages)

    def broadcast_messages(self, data):
        print self._address, "User said:", data[:-1]
        for conn in Connection._conns:
            conn.send_message(data)
        self.read_message()
    
    def send_message(self, data):
        self._stream.write(data)
        
    def on_close(self):
        print self._address, "A user has left the chat room."
        Connection._conns.remove(self)

class ChatServer(TCPServer):
    def handle_stream(self, stream, address):        
        Connection(stream, address)

if __name__ == '__main__':
    print "begin..."
    server = ChatServer()
    server.listen(8000)
    IOLoop.instance().start()    

其它版本的tornado chat server參見

http://www.keakon.net/2011/10/02/Tornado%E7%9A%84IOStream%E7%AE%80%E4%BB%8B%E4%B8%8E%E5%BA%94%E7%94%A8

https://github.com/facebook/tornado/blob/master/demos/chat/chatdemo.py

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐