初识tornado和tornado websocket

本文介绍Tornado Web框架的基础知识及使用方法,并提供了一个结合WebSocket功能的实例,演示了前后端交互过程。

tornado是什么

Tornado是一个轻量级的Web框架,异步非阻塞+内置WebSocket功能。

安装:pip3 install tornado

 

tornado websocket示例

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


class IndexHandler(RequestHandler):
    def get(self, *args, **kwargs):
        # self.write('Hello World')
        self.render('index.html')

    def post(self, *args, **kwargs):
        user = self.get_argument('user')
        self.write('成功')


WS_LIST = []


class MessageHandler(WebSocketHandler):
    def open(self, *args, **kwargs):
        WS_LIST.append(self)

    def on_message(self, message):
        for ws in WS_LIST:
            ws.write_message(message)

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


settings = {
    'template_path': 'templates',
    'static_path': 'static',
}

app = Application([
    (r"/index", IndexHandler),
    (r"/message", MessageHandler),
], **settings)

if __name__ == '__main__':
    app.listen(address='0.0.0.0', port=9999)
    tornado.ioloop.IOLoop.instance().start()

前端页面:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>
        .msg-item{
            padding: 5px;
            border: 1px;
            margin: 0 5px;
        }
    </style>
</head>
<body>
    <h1>首页</h1>
    <div>
        <h2>发送消息</h2>
        <input id="msg" type="text"  /> <input type="button" value="发送" onclick="sendMsg()">
        <h2>接收消息</h2>
        <div id="container">

        </div>
    </div>

    <script src="/static/jquery-3.3.1.min.js"></script>
    <script>

        ws = new WebSocket('ws://192.168.12.42:9999/message');
        ws.onmessage = function (event) {
            var tag = document.createElement('div');
            tag.className = 'msg-item';
            tag.innerText = event.data;
            $('#container').append(tag);
        }
        ws.onclose = function (event) {
            // 服务端主动断开了连接
        }
        function sendMsg() {
            ws.send($('#msg').val());
        }

        // 客户端要断开连接
        // ws.close()
    </script>
</body>
</html>

 

转载于:https://www.cnblogs.com/weiwu1578/articles/9053030.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值