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

时间:2013-05-17 11:50:04

标签: javascript python websocket

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

web_socket.send("text to be sent") 

和(python)

data = web_socket.recv(1024)
print data 

他们会在服务器网站上收到他们想要的东西,清晰且好的打印输出“要发送的文字”。

您可以在下面找到我的.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)

3 个答案:

答案 0 :(得分:1)

我正在做类似的事情。 Websocket协议要求客户端使用掩码发送其所有数据。这就是为什么你看到'垃圾' - 它是蒙面文本。

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

  

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

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

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

答案 1 :(得分:0)

要从服务器端向websocket客户端发送消息,您需要执行以下操作:

message = bytearray([0b10000001, len(original_msg)])

for byte in bytearray(original_msg): 
    message.append(byte)

https://github.com/westial/SingleSocket

处查看稳定的服务器到客户端单向套接字库

答案 2 :(得分:-1)

垃圾数据的问题是javascript代码发送了屏蔽数据,您必须在服务器端取消屏蔽它,服务器将未屏蔽的数据发送到客户端。要解决此问题,请参阅我的git-hub页面  [] [1] https://github.com/mohanbe/web-chat