Tornado-第三篇-tornado支持websocket协议

本文介绍使用Python的Tornado框架实现WebSocket实时通讯的具体代码。通过定义WebSocketHandler子类MsgHandler,实现消息的接收和广播功能,同时提供了一个用于渲染首页的HomeHandler。配置了模板路径和cookie密钥,监听8888端口。

  manage.py

from tornado.ioloop import IOLoop
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler
from tornado.web import Application

CLIENT_LIST = []


class MsgHandler(WebSocketHandler):
    def open(self):
        CLIENT_LIST.append(self)

    def on_message(self, message):
        for obj in CLIENT_LIST:
            obj.write_message(message)

    def on_close(self):
        CLIENT_LIST.remove(self)


# 页面函数
class HomeHandler(RequestHandler):
    def get(self, *args, **kwargs):
        self.render('index.html')


# 配置
settings = {
    'template_path': 'templates',
    'cookie_secret': 'asq3wuraldf'
}
# 页面对应函数
application = Application([
    ('/home', HomeHandler),
    ('/msg', MsgHandler),
], **settings)
if __name__ == '__main__':
    application.listen(8888)
    IOLoop.instance().start()

  

转载于:https://www.cnblogs.com/weilaixiaochaoren/p/10276257.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值