websocket原生、flask\tornado实现

定义

  • 什么是轮训?
    - 通过定时器让程序每隔n秒执行一次操作。
  • 什么是长轮训?
    - 浏览器向后端发起请求,后端会将请求 hang 住,最多hang 30s。
    如果一直不返回数据:则最多等待30s,紧接着用户立即再发送请求。
    如果有数据返回:则操作数据并立即再发送请求。
    PS:后台可以使用队列或redis的列表来hang主请求。

  • 轮训和长轮训目的?
    由于Http请求是无状态、短连接所以服务端无法向客户端实时推送消息,
    所以,我们就是可以使用:轮训和长轮训去服务端获取实时数据。

websocket是什么?

websocket是一套类似于http的协议。
扩展:
http协议:\r\n分割、请求头和请求体\r\n分割、无状态、短连接。
websocket协议:\r\n分割、创建连接后不断开、 验证+数据加密;

websocket本质:

  • 就是一个创建连接后不断开的socket,当连接成功之后:
  • 客户端(浏览器)会自动向服务端发送消息,包含: Sec-WebSocket-Key: iyRe1KMHi4S4QXzcoboMmw==
  • 服务端接收之后,会对于该数据进行加密:
    base64(sha1(swk + magic_string))

  • 构造响应头:
    HTTP/1.1 101 Switching Protocols\r\n
    Upgrade:websocket\r\n
    Connection: Upgrade\r\n
    Sec-WebSocket-Accept: 加密后的值\r\n
    WebSocket-Location: ws://127.0.0.1:8002\r\n\r\n

  • 发给客户端(浏览器)
    - 建立:双工通道,接下来就可以进行收发数据
    - 发送的数据是加密,解密,根据payload_len的值进行处理:
    - payload_len <=125
    - payload_len ==126
    - payload_len ==127
    - 获取内容:
    - mask_key
    - 数据
    根据mask_key和数据进行位运算,就可以把值解析出来。

示例

创建socket、绑定、监听、等待数据、接受数据
解析头部构造字典、base64加密、构造响应头、发送、客户端校验

客户端通过ws.seng()发送请求、服务端接受、并且send_msg加密发送

页面端

<body>
    <script>
        // 向127.0.0.1:8002发送一个websocket请求
        ws = new WebSocket('ws://127.0.0.1:8002/')
        ws.onmessage = function (event) {
            console.log(event.data);
        }
    </script>
</body>

后台端

import socket
import base64
import hashlib

def get_headers(data):
    """
    将请求头格式化成字典
    :param data:
    :return:
    """
    header_dict = {}
    data = str(data, encoding='utf-8')
    header, body = data.split('\r\n\r\n', 1)
    header_list = header.split('\r\n')
    for i in range(0, len(header_list)):
        if i == 0:
            if len(header_list[i].split(' ')) == 3:
                header_dict['method'], header_dict['url'], header_dict['protocol'] = header_list[i].split(' ')
        else:
            k, v = header_list[i].split(':', 1)
            header_dict[k] = v.strip()
    return header_dict

def send_msg(conn, msg_bytes):
    """
    WebSocket服务端向客户端发送消息
    :param conn: 客户端连接到服务器端的socket对象,即: conn,address = socket.accept()
    :param msg_bytes: 向客户端发送的字节
    :return:
    """
    import struct

    token = b"\x81"
    length = len(msg_bytes)
    if length < 126:
        token += struct.pack("B", length)
    elif length <= 0xFFFF:
        token += struct.pack("!BH", 126, length)
    else:
        token += struct.pack("!BQ", 127, length)

    msg = token + msg_bytes
    conn.send(msg)
    return True

#构造socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('127.0.0.1', 8002))
sock.listen(5)
# 等待用户连接
conn, address = sock.accept()
#接受请求数据
data = conn.recv(8096)

#解析请求头数据
header_dict = get_headers(data)
print("---header_dict---",header_dict)
# 在验证环节对Sec-WebSocket-Key对应的值进行加密

#加密
magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
value = header_dict['Sec-WebSocket-Key'] + magic_string
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())


# 构造响应头
response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \
      "Upgrade:websocket\r\n" \
      "Connection: Upgrade\r\n" \
      "Sec-WebSocket-Accept: %s\r\n" \
      "WebSocket-Location: ws://127.0.0.1:8002\r\n\r\n"

response = response_tpl %(str(ac,encoding='utf-8'),)

conn.sendall(bytes(response,encoding='utf-8'))


while True:
    # 用户发过来的加密的数据
    info = conn.recv(8096)
    payload_len = info[1] & 127
    if payload_len == 127:
        extend_payload_len = info[2:10]
        mask = info[10:14]
        decoded = info[14:]
    elif payload_len == 126:
        extend_payload_len = info[2:4]
        mask = info[4:8]
        decoded = info[8:]
    else:
        extend_payload_len = None
        mask = info[2:6]
        decoded = info[6:]

    bytes_list = bytearray()
    for i in range(len(decoded)):
        chunk = decoded[i] ^ mask[i % 4]
        bytes_list.append(chunk)
    body = str(bytes_list, encoding='utf-8')
    print("----body---",body)

    body = body + 'sb'

    send_msg(conn,bytes(body,encoding='utf-8'))

这里写图片描述
后台输出如下:

  • —header_dict— {‘method’: ‘GET’, ‘url’: ‘/’, ‘protocol’: ‘HTTP/1.1’, ‘Host’: ‘127.0.0.1:8002’, ‘Connection’: ‘Upgrade’, ‘Pragma’: ‘no-cache’, ‘Cache-Control’: ‘no-cache’, ‘Upgrade’: ‘websocket’, ‘Origin’: ‘http://localhost:63342‘, ‘Sec-WebSocket-Version’: ‘13’, ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36’, ‘Accept-Encoding’: ‘gzip, deflate, br’, ‘Accept-Language’: ‘zh-CN,zh;q=0.9’, ‘Cookie’: ‘csrftoken=Ksr2UHM7d5OLjgn6oDeqmywTY6diTZLUH0tbTlrWrVvLzvMhlB4KdnvvsFAhzFj2’, ‘Sec-WebSocket-Key’: ‘mmsKRyDDiMjZynOFubTQkg==’, ‘Sec-WebSocket-Extensions’: ‘permessage-deflate; client_max_window_bits’}

  • —-body— websocket

flask实现websocket

安装

pip3 install gevent-websocket

前端代码

<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://127.0.0.1:5000/test');
        ws.onmessage = function (event) {
            var tag = document.createElement('div');
            tag.className = 'msg-item';
            tag.innerText = event.data;
            $('#container').append(tag);
        }

        function sendMsg() {
            ws.send($('#msg').val());
        }
    </script>
</body>

后端代码

from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask, render_template, request
import pickle

app = Flask(__name__)
app.secret_key = 'xfsdfqw'


@app.route('/index')
def index():
    return render_template('index.html')


WS_LIST = []


@app.route('/test')
def test():
    ws = request.environ.get('wsgi.websocket')
    if not ws:
        return '请使用WebSocket协议'
    # websocket连接已经成功
    WS_LIST.append(ws)
    while True:
        # 等待用户发送消息,并接受
        message = ws.receive()

        # 关闭:message=None
        if not message:
            print("ws.close")
            WS_LIST.remove(ws)
            ws.close()
            break

        for item in WS_LIST:
            item.send(message)

    return "asdfasdf"


if __name__ == '__main__':
    http_server = WSGIServer(('127.0.0.1', 5000,), app, handler_class=WebSocketHandler)
    http_server.serve_forever()

测试效果
这里写图片描述

tornado实现

什么是Tornado?
Tornado是一个轻量级的Web框架,异步非阻塞+内置WebSocket功能。
安装:
pip3 install tornado

前端代码

<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://127.0.0.1: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>

后端代码

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 check_origin(self, origin):
        return True

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

    def on_message(self, message):
        # self.close() 服务端主动断开连接,客户端的onclose方法自动执行
        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='127.0.0.1', port=9999)
    tornado.ioloop.IOLoop.instance().start()

这里写图片描述

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013210620/article/details/80355813
个人分类: PythonWeb框架
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭