【发布时间】:2016-08-24 15:02:02
【问题描述】:
我正在尝试使用扭曲的 websocket 服务器并将其连接到本地主机上的 javascript 客户端,而不是通过网络。服务器和客户端可以看到对方,但他们无法完成握手。是的,由于系统要求,我正在使用 txWS 提供的 Hixie-76 包装器。
我很困惑为什么他们无法连接?
版本:高速公路 0.16,扭曲 0.16.3
这是我想要实现的实际示例: https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket/echo 使用 server.py 和 client.html
日志:
2016-08-24 15:44:33+0100 [-] Log opened.
2016-08-24 15:44:33+0100 [-] WebSocketServerFactory (WebSocketFactory) starting on 8080
2016-08-24 15:44:33+0100 [-] Starting factory <autobahn.twisted.websocket.WebSocketServerFactory object at 0x00000000031DB7F0>
2016-08-24 15:44:33+0100 [-] Starting factory <txws.WebSocketFactory instance at 0x0000000002FA82C8>
2016-08-24 15:44:34+0100 [MyServerProtocol (WebSocketProtocol),0,127.0.0.1] Starting HyBi-00/Hixie-76 handshake
2016-08-24 15:44:34+0100 [MyServerProtocol (WebSocketProtocol),0,127.0.0.1] Completed HyBi-00/Hixie-76 handshake
2016-08-24 15:44:39+0100 [-] WebSocket connection closed:
2016-08-24 15:44:39+0100 [-] False
2016-08-24 15:44:39+0100 [-] 1006
2016-08-24 15:44:39+0100 [-] connection was closed uncleanly (peer did not finish (in time) the opening handshake)
Python 类:
from txws import WebSocketFactory
from twisted.internet import reactor
from twisted.python import log
from autobahn.twisted.websocket import WebSocketServerFactory
from autobahn.twisted.websocket import WebSocketServerProtocol
import json
import sys
class MyServerProtocol(WebSocketServerProtocol):
def onMessage(self, payload, isBinary):
print "Message Received!!!!"
msg = json.dumps({'status':'PLEASE WORK'})
self.sendMessage(msg, isBinary=False)
def onClose(self, wasClean, code, reason):
print "WebSocket connection closed: "
print str(wasClean)
print str(code)
print str(reason)
def make_server():
print 'Making ws server'
log.startLogging(sys.stdout)
factory = WebSocketServerFactory("ws://127.0.0.1:8080")
factory.protocol = MyServerProtocol
reactor.listenTCP(8080, WebSocketFactory(factory)) #txWS WebSocketFactory wrapper
reactor.run()
Javascript:
function ConnectWebSocket() {
websocket = new WebSocket('ws://127.0.0.1:8080');
websocket_open = true;
websocket.onopen = function(e) {
console.log('opened');
console.log(e);
websocket.send('slow test');
};
websocket.onclose = function(e) {
console.log("Connection closed.");
websocket_open = false;
websocket = null;
ConnectWebSocket();
};
websocket.onmessage = function(e) {
console.log('message');
console.log(e.data);
};
websocket.onerror = function(e) {
console.log('error');
console.log(e);
};
}
ConnectWebSocket();
【问题讨论】:
-
我能看到的唯一可能是问题的是
(u"ws://127.0.0.1:8080")中缺少“u”这只是将字符串标记为 unicode,据我了解,这通常不是什么大问题.我从未使用过 Hixie-76 包装器,所以我猜WebSocketFactory(factory)是问题所在,因为其他一切看起来都不错。
标签: javascript python websocket twisted autobahn