WebStocket后端代码:
import socket
import base64
import hashlib
import time
import json
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
def WebStocket(parameters_data,ip,port):
print('Waiting for connection...')
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((ip,port))
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.listen()
conn,addr = sock.accept()
content = conn.recv(1024)
#print(content)
headers = get_headers(content)
#print(headers)
magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
value = headers["Sec-WebSocket-Key"] + magic_string
hash_str = base64.b64encode(hashlib.sha1(bytes(value, encoding='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://%s%s\r\n\r\n"
response_str = response_tpl % (str(hash_str, encoding='utf-8'), headers['Host'], headers['url'])
conn.send(bytes(response_str, encoding='utf-8'))
print('Successful connection!')
print('Start sending data:')
js_data = json.dumps(parameters_data)#数据JSON化
send_msg(conn, bytes(js_data, encoding="utf-8"))
print('Successful Send :%s'%(parameters_data))
if __name__ == '__main__':
ip = 'localhost' #建立连接的ip
port = 8002 #建立连接的port端口号
parameters_data = {'WebStocket':'hello word'} #向前端发送的数据
WebStocket(parameters_data,ip,port)
WebStocket前端代码:
//将下列代码插入到前端script中即可
var ws = new WebSocket("ws://localhost:8002"); #此处的地址与WebStocket后端相一致
ws.onopen = function () {
ws.send([model_id_value,algo_id_value]);
// alert("sending:\n this is test data ");
};
ws.onmessage = function (evt) {
//接受由后端传送的数据
var received_msg = evt.data;
getdata = JSON.parse(received_msg)
getdata = getdata['WebStocket']
alert(getdata)
};
ws.onclose = function () {
alert("数据通道关闭");
};