websocket原理、加密、解密
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\s\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.send()发送请求、服务器接收,并且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’}
flask实现websocket
安装
pip3 install genvent-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()
测试效果