WebSocket javascript客户端和python服务器。检索输出中的垃圾 [英] WebSocket javascript client and python server. Retrieving garbage in output

查看:78
本文介绍了WebSocket javascript客户端和python服务器。检索输出中的垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从浏览器客户端向python服务器发送字符串/文本数据,然后将其打印出来。我在互联网上关注了几个例子,并且都是一样的:使用 javascript

I am trying to send string/text data from browser client to python server and simply print it out. I have followed several examples on the internet, and all are the same: by using javascript

web_socket.send("text to be sent") 

和(python)

data = web_socket.recv(1024)
print data 

他们收到了他们想要的东西,在服务器网站上打印出来的文本是什么。

they receive what they want, what is clear and nice printout "text to be sent" on server site.

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

You can find my .html and .py below:

<!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时):

And server printout (when input was like "AA", or "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协议要求客户端使用掩码发送其所有数据。这就是为什么你看到'垃圾' - 它是被掩盖的文本。

I'm working on something similar myself. The Websocket protocol mandates that the client sends all its data using a mask. This is why you see 'garbage' - it's the masked text.

http://tools.ietf.org/html/rfc6455#section-5


客户端必须屏蔽
发送给服务器的所有帧

"a client MUST mask all frames that it sends to the server"

阅读协议的第5部分会变得清晰。浏览器(即客户端)正在实现协议(当您调用ws.send时)。你需要做点什么。

Read section 5 of the protocol and all will become clear. The browser (ie the client) is just implementing the protocol as it should (when you call ws.send). You need to do your bit.

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

Note also that when the sever sends data to the client it must NOT mask. But it still has to supply other info before the actual data (type, length etc).

这篇关于WebSocket javascript客户端和python服务器。检索输出中的垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆