我在尝试使用 WebSockets 在 python 和 javascript 之间进行通信时遇到问题。
这是我的 python 服务器(ws.py),它只打印出它接收到的任何数据并将其重新发送到客户端:
#!/usr/bin/env python
# Echo server program
import socket
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
print 'Data recieved =', data
conn.sendall(data)
conn.close()
这适用于 netcat 使用nc localhost 50007
,但是当我尝试使用我的 html/Javascript 客户端时,我得到了一个连接,但服务器没有收到消息,我只是得到以下信息:
Connected by ('127.0.0.1', 62264)
Data recieved = GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:50007
Origin: http://localhost
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: 6hxDWShxMnFxwGYAWym+eg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
Cookie: SQLiteManager_currentLangue=2
这就是我在 Chrome 中获得控制台的内容:
WebSocket connection to 'ws://localhost:50007/' failed: basicWSoc.html:7
Error Logged: [object Event]
这是我的网络客户端(basicWSoc.html)
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
var connection=new WebSocket("ws://localhost:50007");
connection.onopen = function () {
connection.send('Hello, Server!!'); //send a message to server once connection is opened.
};
connection.onerror = function (error) {
console.log('Error Logged: ' + error); //log errors
};
connection.onmessage = function (e) {
console.log('Received From Server: ' + e.data); //log the received message
};
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>
现在我仍然是 python 的新手,Web 套接字对我来说是全新的,所以我可能忽略了显而易见的......
任何帮助将不胜感激