WebSocket
WebSocket
简介
1.HTTP协议: http://baidu.com
一次请求 一次响应 断开,无状态 。记录状态 session or cookie
轮询:
94 - 2002
每一秒钟发送600次请求 一次收取100条数据
浪费资源 - 服务器处理资源 - 客户端发请求浪费处理资源 - 序列化消息浪费处理资源
优点:消息基本实时
缺点:双资源浪费
ICQ : 轮询 - 就是QQ - OICQ - 2000
长轮询:
2000 - ~
客户端发送一个请求 - 服务器接收请求 - 不返回 - 阻塞等待客户端的消息 - 如果有消息了 - 返回给客户端 - 断开
瞬间重连 - 客户端发送一个请求
服务器底层小循环,占用极小资源
缺点:断开重连次数过多(如果消息很频繁)
优点:节省了部分资源,数据实时性略差
2.WebSocket协议: ws://baidu.com
一次请求 - 服务器收到请求 开始和客户端握手 - 保持长连接 - 数据实时 - 连接永远保持(除非用户关闭或者服务器宕机)
优点:长连接 并且不影响 收发请求
缺点:连接保持,是需要资源的
websocket 原理
WebSocket是一种计算机通信协议,通过单个TCP连接提供全双工通信通道。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
websocket 握手
客户端握手请求
GET /chat HTTP/1.1
Host: example.com:8000
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
服务器握手相应
当服务器收到客户端发来的请求时,将注意到请求头,表明客户端有意将HTTP协议升级为WebSocket协议。同时服务端将返回相应,确认socket连接建立。
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
请求参数:
- Connection必须设置Upgrade,表示客户端希望连接升级。
- Upgrade字段必须设置Websocket,表示希望升级到Websocket协议。
- Sec-WebSocket-Key是随机的字符串,服务器端会用这些数据来构造出一个SHA-1的信息摘要。把“Sec-WebSocket-Key”加上一个特殊字符串“258EAFA5-E914-47DA-95CA-C5AB0DC85B11”,然后计算SHA-1摘要,之后进行BASE-64编码,将结果做为“Sec-WebSocket-Accept”头的值,返回给客户端。如此操作,可以尽量避免普通HTTP请求被误认为Websocket协议。
- Sec-WebSocket-Version 表示支持的Websocket版本。RFC6455要求使用的版本是13,之前草案的版本均应当弃用。
基于 pyhton 的示例
py
import socket, base64, hashlib
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('127.0.0.1', 9527))
sock.listen(5)
# 获取客户端socket对象
conn, address = sock.accept()
# 获取客户端的【握手】信息
data = conn.recv(1024)
magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' # 特殊字符串
def get_header(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
headers = get_header(data) # 提取请求头信息
# 对请求头中的sec-websocket-key进行加密
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:9527\r\n\r\n"
value = headers['Sec-WebSocket-Key'] + magic_string
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
response_str = response_tpl % (ac.decode('utf-8'))
# 响应【握手】信息
conn.send(response_str.encode("utf8"))
while True:
msg = conn.recv(8096)
print(msg)
html
<script type="text/javascript">
var socket = new WebSocket("ws://127.0.0.1:9527");
...
</script>
客户端和服务端收发数据-数据解析
客户端和服务端传输数据时,需要对数据进行【封包】和【解包】。客户端的JavaScript类库已经封装【封包】和【解包】过程,但Socket服务端需要手动实现。
获取客户端发送的数据【解包】
info = b'\x81\x85\x018\xf9\xd0i]\x95\xbcn' # hello
payload_len = info[1] & 127
if payload_len == 126:
extend_payload_len = info[2:4]
mask = info[4:8]
decoded = info[8:]
# 当位运算结果等于126时,则第3-4个字节为数据长度
# 第5-8字节为mask 解包所需
# 则数据为第9字节至结尾
elif payload_len == 127:
extend_payload_len = info[2:10]
mask = info[10:14]
decoded = info[14:]
# 当位运算结果等于127时,则第3-10个字节为数据长度
# 第11-14字节为mask 解包所需
# 则数据为第15字节至结尾
else:
extend_payload_len = None
mask = info[2:6]
decoded = info[6:]
# 当位运算结果小于等于125时,则这个数字就是数据的长度
# 第3-6字节为mask 解包所需
# 则数据为第7字节至结尾
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) # hello
向客户端发送数据【封包】,注意 前后端解包、分包不一样
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 <= 254:
token += struct.pack("B", length)
elif length <= 65535:
token += struct.pack("!BH", 126, length)
else:
token += struct.pack("!BQ", 127, length)
msg = token + msg_bytes
conn.send(msg)
return True
合集
基于Python socket实现的WebSocket服务端:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
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 <= 254:
token += struct.pack("B", length)
elif length <= 65535:
token += struct.pack("!BH", 126, length)
else:
token += struct.pack("!BQ", 127, length)
msg = token + msg_bytes
conn.send(msg)
return True
def run():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('127.0.0.1', 8003))
sock.listen(5)
conn, address = sock.accept()
data = conn.recv(1024)
headers = get_headers(data)
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://%s%s\r\n\r\n"
value = headers['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
response_str = response_tpl % (ac.decode('utf-8'), headers['Host'], headers['url'])
conn.send(bytes(response_str, encoding='utf-8'))
while True:
try:
info = conn.recv(8096)
except Exception as e:
info = None
if not info:
break
payload_len = info[1] & 127
if payload_len == 126:
extend_payload_len = info[2:4]
mask = info[4:8]
decoded = info[8:]
elif payload_len == 127:
extend_payload_len = info[2:10]
mask = info[10:14]
decoded = info[14:]
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')
send_msg(conn, body.encode('utf-8'))
sock.close()
if __name__ == '__main__':
run()
利用JavaScript类库实现客户端
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<input type="text" id="txt"/>
<input type="button" id="btn" value="提交" onclick="sendMsg();"/>
<input type="button" id="close" value="关闭连接" onclick="closeConn();"/>
</div>
<div id="content"></div>
<script type="text/javascript">
var socket = new WebSocket("ws://127.0.0.1:8003/chatsocket");
socket.onopen = function () {
/* 与服务器端连接成功后,自动执行 */
var newTag = document.createElement('div');
newTag.innerHTML = "【连接成功】";
document.getElementById('content').appendChild(newTag);
};
socket.onmessage = function (event) {
/* 服务器端向客户端发送数据时,自动执行 */
var response = event.data;
var newTag = document.createElement('div');
newTag.innerHTML = response;
document.getElementById('content').appendChild(newTag);
};
socket.onclose = function (event) {
/* 服务器端主动断开连接时,自动执行 */
var newTag = document.createElement('div');
newTag.innerHTML = "【关闭连接】";
document.getElementById('content').appendChild(newTag);
};
function sendMsg() {
var txt = document.getElementById('txt');
socket.send(txt.value);
txt.value = "";
}
function closeConn() {
socket.close();
var newTag = document.createElement('div');
newTag.innerHTML = "【关闭连接】";
document.getElementById('content').appendChild(newTag);
}
</script>
</body>
</html>
Python + Flask 实现 WebSocket 通讯:
安装 gevent-websocket ,pip install gevent-websocket
实现websocket通信
通过前端中的 console控制台中,发送信息ws.send("message");
,就能收到信息。
view
"""websocket"""
from geventwebsocket.server import WSGIServer # WSGI提供服务
from geventwebsocket.handler import WebSocketHandler # WSGI遇到WS协议时的处理方式
from geventwebsocket.websocket import WebSocket # 语法提示
from flask import Flask, request
# 基于 Flask + geventwebsocket
app = Flask(__name__)
@app.route('/ws')
def ws_func():
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
# web + socket
print(user_socket)
while True:
msg = user_socket.receive() # 等待客户端发过来的消息
print(msg)
# 返回相同的消息给客户端
user_socket.send(msg)
if __name__ == '__main__':
http_serv = WSGIServer(('0.0.0.0', 9527), application=app, handler_class=WebSocketHandler)
http_serv.serve_forever()
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ws</title>
</head>
<body>
</body>
<script>
let ws = new WebSocket('ws://127.0.0.1:9527/ws');
// 当 ws 收到消息时执行 onmessage 属性
ws.onmessage = function (ws_data) {
console.log(ws_data);
console.log(ws_data.data);
}
</script>
</html>
websocket 群聊
多个用户 访问 http://127.0.0.1/chat
,可以发送消息,可以收到别人发的消息
view
"""websocket"""
from geventwebsocket.server import WSGIServer # WSGI提供服务
from geventwebsocket.handler import WebSocketHandler # WSGI遇到WS协议时的处理方式
from geventwebsocket.websocket import WebSocket # 语法提示
from flask import Flask, request, render_template
# 基于 Flask + geventwebsocket
app = Flask(__name__)
socket_list = []
@app.route('/ws')
def ws_func():
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
# web + socket
print(user_socket)
socket_list.append(user_socket)
while True:
msg = user_socket.receive() # 等待待接收客户端发过来的消息
print(msg)
for socket in socket_list:
if socket == user_socket:
continue
try:
# 链接断掉 socket会变成NoneType
socket.send(msg)
except:
continue
@app.route('/chat')
def group_chat():
return render_template('group_chat.html')
if __name__ == '__main__':
http_serv = WSGIServer(('0.0.0.0', 9527), application=app, handler_class=WebSocketHandler)
http_serv.serve_forever()
group_chat.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>group_chat</title>
</head>
<body>
<div>
<div>
<input type="text" id="message">
<button onclick="send_msg()">发送</button>
</div>
<div id="msg_list">
</div>
</div>
</body>
<script>
let ws = new WebSocket('ws://127.0.0.1:9527/ws');
ws.onmessage = function (event) {
let recv_msg = event.data;
let p = document.createElement('p');
p.innerText = recv_msg;
console.log(recv_msg);
document.getElementById('msg_list').appendChild(p);
};
function send_msg() {
let send_msg = document.getElementById('message').value;
ws.send(send_msg);
}
</script>
</html>
websocket 单聊
访问 http://127.0.0.1:9527/chat
登录后,可以向其他用户发消息,也可以收到其他用户的消息
view
"""websocket"""
from geventwebsocket.server import WSGIServer # WSGI提供服务
from geventwebsocket.handler import WebSocketHandler # WSGI遇到WS协议时的处理方式
from geventwebsocket.websocket import WebSocket # 语法提示
from flask import Flask, request, render_template
import json
# 基于 Flask + geventwebsocket
app = Flask(__name__)
socket_dict = {}
@app.route('/ws/<string:user_name>')
def ws_func(user_name):
user_socket = request.environ.get('wsgi.websocket') # type:WebSocket
print(user_socket)
socket_dict[user_name] = user_socket
"""
socket_dict {
user_name:user_socket,
}
"""
while True:
"""
msg:{
from_user:
to_user:
info:
}
"""
msg = user_socket.receive()
if not msg:
socket_dict.pop(user_name)
# 当客户端断开连接时,msg为空
break
data = json.loads(msg)
print(data)
# from_user = data.get('from_user')
to_user = data.get('to_user')
# info = data.get('info')
for user in socket_dict:
if user == to_user:
try:
# 链接断掉 socket会变成NoneType
socket_dict[user].send(msg)
except:
break
return '' # 当客户端断开连接时,会到这里
@app.route('/chat')
def chat_one():
return render_template('chat_one.html')
if __name__ == '__main__':
http_serv = WSGIServer(('0.0.0.0', 9527), application=app, handler_class=WebSocketHandler)
http_serv.serve_forever()
chat_one.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>chat_one</title>
</head>
<body>
<div>
<div>
<input type="text" name="" id="login">
<button onclick="login()">登录</button>
</div>
<br>
<div>
<p>to_user:<input type="text" name="" id="to_user"></p>
<p>info:<input type="text" name="" id="info"></p>
<button onclick="send_info()">发送</button>
</div>
<div id="info_list">
</div>
</div>
</body>
<script>
let ws = null;
let user_name = null;
function login() {
user_name = document.getElementById('login').value;
ws = new WebSocket('ws://127.0.0.1:9527/ws/' + user_name);
ws.onmessage = function (event) {
let data = event.data;
data = JSON.parse(data);
let from_user = data.from_user;
let info = data.info;
let tagP = document.createElement('p');
tagP.innerText = from_user + " : " + info;
document.getElementById('info_list').appendChild(tagP);
}
}
function send_info() {
let info = document.getElementById('info').value;
let to_user = document.getElementById('to_user').value;
let data = {
from_user: user_name,
to_user: to_user,
info: info
};
console.log(data);
data = JSON.stringify(data);
console.log(data);
ws.send(data);
}
</script>
</html>