我试图将字符串/文本数据从浏览器客户端发送到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 Protocolsrn"
"Upgrade: WebSocketrn"
"Connection: Upgradern"
"Sec-WebSocket-Accept: " + accept_key + "rnrn")
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协议要求客户端使用掩码发送所有数据。这就是为什么你看到'垃圾' -这是蒙版文本。
https://www.rfc-editor.org/rfc/rfc6455
第5节"客户端必须屏蔽所有的帧发送到服务器"
阅读协议的第5节,一切都会变得清晰。浏览器(即客户端)只是实现协议,因为它应该(当你调用ws.send)。你得尽你的一份力。
还要注意,当服务器向客户端发送数据时,它必须不掩码。但是它仍然需要在实际数据(类型,长度等)之前提供其他信息。
要从服务器端发送消息到websocket客户端,您需要做以下操作:
message = bytearray([0b10000001, len(original_msg)])
for byte in bytearray(original_msg):
message.append(byte)
查看稳定的服务器到客户端单向套接字库https://github.com/westial/SingleSocket
垃圾数据的问题是javascript代码发送被屏蔽的数据,你必须在服务器端揭开它的掩码,然后服务器将揭开的数据发送到客户端。要解决这个问题,请参阅我的git-hub页面[] [1] https://github.com/mohanbe/web-chat