实现简单的对话程序,代码如下:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
import socket
import base64
import hashlib
import threading
def get_headers(data):
headers = {}
data = str(data, encoding='utf-8')
header, body = data.split('\r\n\r\n', 1)
header_list = header.split('\r\n')
for i in header_list:
i_list = i.split(':', 1)
if len(i_list) >= 2:
headers[i_list[0]] = "".join(i_list[1::]).split()
else:
i_list = i.split(" ", 1)
if i_list and len(i_list) == 2:
headers["method"] = i_list[0]
headers["protocol"] = i_list[1]
return headers
def send_msg(conn, msg_bytes):
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.sendall(msg)
return True
# 解码
def parse_payload(payload):
payload_len = payload[1] & 127
if payload_len == 126:
extend_payload_len = payload[2:4]
mask = payload[4:8]
decoded = payload[8:]
elif payload_len == 127:
extend_payload_len = payload[2:10]
mask = payload[10:14]
decoded = payload[14:]
else:
extend_payload_len = None
mask = payload[2:6]
decoded = payload[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')
return body
# 建立连接
def handler_accept(socke):
while True:
sock, addr = socke.accept()
data = socke.recv(8096)
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\r\n\r\n"
magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
if headers.get('Sec-WebSocket-Key'):
value = headers['Sec-WebSocket-Key'][0] + magic_string
ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest())
response_str = response_tpl % (ac.decode('utf-8'), headers.get("Host"))
sock.sendall(bytes(response_str, encoding="utf-8"))
t = threading.Thread(target=handler_msg, args=(sock,))
t.start()
# 回应网页客户端的信息
def handler_msg(sock):
with sock as c:
while True:
data_recv = c.recv(8096)
if data_recv[0:1] == b'\x81':
data_recv = parse_payload(data_recv)
if data_recv == "你好呀":
send_msg(c, bytes('你好,请问你需要什么帮助?', encoding='utf-8'))
elif data_recv == "退出":
break
sock.close()
# 启动本地服务
def server_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", 5000))
sock.listen(5)
# 启动线程
t = threading.Thread(target=handler_accept(sock))
if __name__ == '__main__':
server_socket()
HTML页面的代码: