python 怎么解析 websocket 传来的汉字 乱码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 怎么解析 websocket 传来的汉字 乱码相关的知识,希望对你有一定的参考价值。

参考技术A 使用socket的时候,如果你传送的是str类型的汉字,就不会出现乱码 参考技术B 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import threading
import hashlib
import socket
import base64
import struct

class WebsocketThread(threading.Thread):
def __init__(self, connection, thread_name, clients):
super(WebsocketThread, self).__init__()
self.conn = connection
self.thread_name = thread_name
self.clients = clients

def run(self):
print('new websocket client joined!')
while True:
data = self.conn.recv(1024)
recv = parse_recv_data(data)
print('recv: ' + recv)
reply = '服务器收到: ' + recv
print(reply)
send_all(self.clients, reply)

def send_all(clients, message):
reply = parse_send_data(message)
for x in clients.values():
x.sendall(reply)

def parse_send_data(data):
if data:
data = str(data)
else:
return False
token = b"\x81"
length = len(data.encode('utf-8'))
if length < 126:
token += struct.pack("B", length)
elif length <= 0xFFFF:
token += struct.pack("!BH", 126, length)
else:
token += struct.pack("!BQ", 127, length)
data = b'%s%s' % (token, data.encode('utf-8'))

return data

def parse_recv_data(msg):
v = msg[1] & 0x7f
if v == 0x7e:
p = 4
elif v == 0x7f:
p = 10
else:
p = 2
mask = msg[p:p + 4]
data = msg[p + 4:]
return ''.join([chr(v ^ mask[k % 4]) for k, v in enumerate(data)])

def generate_token(msg):
key = str(msg) + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
key = key.encode()
ser_key = hashlib.sha1(key).digest()
return base64.b64encode(ser_key)

def handshake(conn):
print('start hanshake !')
headers =
shake = conn.recv(1024).decode('utf-8')
if not len(shake):
return False
print(' len ')
header, data = shake.split('\r\n\r\n', 1)
for line in header.split('\r\n')[1:]:
key, value = line.split(': ', 1)
headers[key] = value
if 'Sec-WebSocket-Key' not in headers:
print('no Sec-WebSocket-Key')
conn.close()
return False

sec_key = headers['Sec-WebSocket-Key']
res_key = generate_token(sec_key)
ret_key = res_key.decode()
ret_origin = headers['Origin']
ret_host = headers['Host']
handshake_string = "HTTP/1.1 101 Switching Protocols\r\n" \
"Upgrade:websocket\r\n" \
"Connection: Upgrade\r\n" \
"Sec-WebSocket-Accept: 1\r\n" \
"WebSocket-Origin: 2\r\n" \
"WebSocket-Location: ws://3/\r\n\r\n"

str_handshake = handshake_string.replace('1', ret_key).replace('2', ret_origin).replace('3', ret_host)
b_handshake = str_handshake.encode()
conn.sendall(b_handshake)

print(' Socket handshaken with success')
return True

if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print('socket set up ')
sock.bind(('127.0.0.1', 3333))
sock.listen(50)
print('cocket binded ')

clients =
count = 0
while True:
try:
connection, address = sock.accept()
print('accept new ')
handshake(connection)
thread_name = 'T' + str(count)
clients[thread_name] = connection
count += 1
thread = WebsocketThread(connection, thread_name, clients)
thread.start()
except socket.timeout:
print('websocket connection timeout')
exit()

javascript code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

<!DOCTYPE html>

</html>

<head>
<meta charset="utf-8">
</head>

<body>
<h3>WebSocketTest</h3>
<div id="login">
<div>
<input id="serverIP" type="text" placeholder="服务器IP" value="127.0.0.1" autofocus="autofocus" />
<input id="serverPort" type="text" placeholder="服务器端口" value="3333" />
<input id="btnConnect" type="button" value="连接" onclick="connect()" />
</div>
<div>
<input id="sendText" type="text" placeholder="发送文本" value="I'm WebSocket Client!" />
<input id="btnSend" type="button" value="发送" onclick="send()" />
</div>
<div>
<div>
来自服务端的消息
</div>
<textarea id="txtContent" cols="50" rows="10" readonly="readonly"></textarea>
</div>
</div>
</body>
<script>
var socket;

function connect()
var host = "ws://" + $("serverIP").value + ":" + $("serverPort").value + "/"
socket = new WebSocket(host);
try

socket.onopen = function(msg)
$("btnConnect").disabled = true;
alert("连接成功!");
;

socket.onmessage = function(msg)
if (typeof msg.data == "string")
displayContent(msg.data);
else
alert("非文本消息");

;

socket.onclose = function(msg) alert("socket closed!") ;
catch (ex)
log(ex);



function send()
var msg = $("sendText").value
socket.send(msg);


window.onbeforeunload = function()
try
socket.close();
socket = null;
catch (ex)
;

function $(id) return document.getElementById(id);

Date.prototype.Format = function(fmt) //author: meizz
var o =
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
;
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;


function displayContent(msg)
$("txtContent").value += "\r\n" + new Date().Format("yyyy/MM/dd hh:mm:ss") + ": " + msg;


function onkey(event) if (event.keyCode == 13) send();
</script>

</html>本回答被提问者采纳

如何播放通过 HTML5 websocket 传来的视频块?

【中文标题】如何播放通过 HTML5 websocket 传来的视频块?【英文标题】:How can I play chunks of a video coming through a HTML5 websocket? 【发布时间】:2012-02-03 01:46:49 【问题描述】:

假设我有一个 ogg 视频。我可以这样玩:

<video  >
<source src="myvideo.ogg" type=video/ogg>
</video>

现在,如果我设法通过 HTML5 websocket 流式传输该视频的 1ko 块 base64 编码,我该如何播放视频?我想不通。如果需要,我可以解码这些块。

提前致谢, 诺利安

【问题讨论】:

对此有何新发现?我也对答案感兴趣...... 【参考方案1】:

看看this。该解决方案与您想要的完全一样!

【讨论】:

以上是关于python 怎么解析 websocket 传来的汉字 乱码的主要内容,如果未能解决你的问题,请参考以下文章

python爬虫 请教一下,python怎么连接websocket

Struts2 怎么获得前台传来json中的 map。

python--websocket数据解析

如何用python解析来自websocket的数据?

如何从 Python 中的 websocket 消息增量解析 JSON?

AJAX如何解析后台传来的json数据?