从客户端向服务器发送数据时遇到问题 - Python websocket。 这是我的客户代码:
<script type="text/javascript">
var s = new WebSocket('ws://127.0.0.1:8999');
s.onopen = function (e) {
console.log("Socket opened.");
};
s.onclose = function (e) {
console.log("Socket closed.");
};
s.onmessage = function(t){alert(t)};
function onSubmit() {
s.send("Hello from client");
}
</script>
服务器 - Python代码:
import socket
import re
from base64 import b64encode
from hashlib import sha1
websocket_answer = (
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: {key} \r\n\r\n',
)
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8999))
s.listen(10)
client, address = s.accept()
text = client.recv(1024)
print "Get data text from client and send back this data: "
print text
key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r\r\n]+', text)
.groups()[0]
.strip())
response_key = b64encode(sha1(key + GUID).digest())
response = '\r\n'.join(websocket_answer).format(key=response_key)
client.send(response)
clientData = client.recv(4096)
client.send("Hello from server")
运行Python Socket Server时,我可以从客户端连接,它的意思是“console.log(”Socket open。“);”工作中。 但是当我通过运行函数onSubmit()数据从客户端向服务器发送数据时,我在Chrome开发工具的控制台日志中收到错误“无效的帧头”。 当我从发送到服务器的客户端(Python文件中的clientData变量)调试数据时,我得到了一个破解字符串:“ Ϭ Ջ ߕ ܉ ”。 有人可以帮我解决这个问题吗?