gpt4 book ai didi

javascript - WebSocket javascript 客户端和 python 服务器。检索输出中的垃圾

转载 作者:行者123 更新时间:2023-11-30 06:32:37 25 4
gpt4 key购买 nike

我正在尝试将字符串/文本数据从浏览器客户端发送到 python 服务器并简单地打印出来。我在网上看了几个例子,都是一样的:通过使用 javascript

web_socket.send("text to be sent") 

和( python )

data = web_socket.recv(1024)
print data

他们收到他们想要的,在服务器站点上清晰 pretty-print 输出“要发送的文本”。

您可以在下面找到我的.html.py:

<!DOCTYPE html>

<html lang="en">
<head>
<title>Test</title>
<script src="jquery.js"></script>
<script type="application/javascript">
var ws;

function init() {
var servermsg = document.getElementById("servermsg");
ws = new WebSocket("ws://127.0.0.1:9877/");
ws.onopen = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server connected";
};
ws.onmessage = function(e){
servermsg.innerHTML = servermsg.innerHTML + "<br><< Recieved data: " + e.data;
};
ws.onclose = function(){
servermsg.innerHTML = servermsg.innerHTML + "<br>Server disconnected";
};
}
function postmsg(){
var text = document.getElementById("message").value;
ws.send(text);
servermsg.innerHTML = servermsg.innerHTML + "<br>>> Data sent: " + text;
}
//$(function(){
// var text = document.getElementById("message").value;
// ws.send(text);
// servermsg.innerHTML = servermsg.innerHTML + "<br>Sent: " + text;
//});


</script>
</head>
<body onload="init();">
<form action="" onSubmit="postmsg();return false;">
<input type="text" name="message" value="" id="message">
<input type="submit" name="submit" value="" id="submit">
</form>
<div id="servermsg"><h1>Message log:</h1></div>
</body>

</html>

服务器:

#!/usr/bin/env python

import socket
import threading
import struct
import hashlib
import base64

PORT = 9877
_address = ""

def create_handshake_resp(handshake):
final_line = ""
lines = handshake.splitlines()
for line in lines:
parts = line.partition(": ")
if parts[0] == "Sec-WebSocket-Key":
key = parts[2]


magic = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

accept_key = base64.b64encode(hashlib.sha1(key+magic).digest())

return (
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: " + accept_key + "\r\n\r\n")


def handle(s, addr):
data = s.recv(1024)
response = create_handshake_resp(data)
s.sendto(response, addr)
lock = threading.Lock()
while 1:
print "Waiting for data from", addr
data = s.recv(1024)
print "Done"
if not data:
print "No data"
break

print 'Data from', addr, ':', data

print 'Client closed:', addr
lock.acquire()
clients.remove(s)
lock.release()
s.close()

def start_server():
print 'STARTING SERVER...'
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', PORT))
s.listen(1)
print 'SERVER STARTED'
while 1:
conn, addr = s.accept()
print 'NEW CONNECTION ['+str(len(clients))+'], connected by ', addr
clients.append(conn)
threading.Thread(target = handle, args = (conn, addr)).start()

clients = []
start_server()

和服务器打印输出(当输入类似于“AA”或“ABC”时):

STARTING SERVER...
SERVER STARTED
NEW CONNECTION [0], connected by ('127.0.0.1', 43877)
Waiting for data from ('127.0.0.1', 43877)
Done
Data from ('127.0.0.1', 43877) : ����w�q
Waiting for data from ('127.0.0.1', 43877)
Done
Data from ('127.0.0.1', 43877) : ��)B�h
Waiting for data from ('127.0.0.1', 43877)

最佳答案

我自己也在做类似的事情。 Websocket 协议(protocol)要求客户端使用掩码发送其所有数据。这就是您看到“垃圾”的原因 - 它是被屏蔽的文本。

https://www.rfc-editor.org/rfc/rfc6455#section-5

"a client MUST mask all frames that itsends to the server"

阅读协议(protocol)的第 5 部分,一切都会变得清晰。浏览器(即客户端)只是按照它应该的方式实现协议(protocol)(当您调用 ws.send 时)。你需要尽你的一份力量。

还请注意,当服务器向客户端发送数据时,它不能屏蔽。但它仍然必须在实际数据(类型、长度等)之前提供其他信息。

关于javascript - WebSocket javascript 客户端和 python 服务器。检索输出中的垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16608296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com