我在尝试使用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()
使用nc localhost 50007
的netcat可以很好地工作,但当我尝试使用我的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]
这是我的web客户端(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套接字对我来说是全新的,所以我可能会过度关注显而易见的。。。。
如有任何帮助,我们将不胜感激
感谢@SLaks向我指出,我使用的TCP套接字与Web套接字相当。我将我的Python服务更改为使用Tornado库,该库实现了web套接字,这使我能够连接到我的web客户端,并在它们之间成功通信