2

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

web_socket.send("text to be sent") 

和(蟒蛇)

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)
4

3 回答 3

1

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

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

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

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

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

于 2013-05-17T14:59:46.187 回答
0

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

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

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

在https://github.com/westial/SingleSocket上查看稳定的服务器到客户端的单向套接字库

于 2015-10-09T15:15:40.080 回答
-1

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

于 2016-07-16T16:58:41.027 回答