在openshift中运行时出现python websocket失败

时间:2018-04-03 01:20:44

标签: python kubernetes openshift twisted autobahn

我有一个在python中运行的autobahn twisted websocket,它正确地在dev vm中工作但是当服务器在openshift中运行时我无法工作。

这是缩短的代码,适用于虚拟机。

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory, listenWS
from autobahn.twisted.resource import WebSocketResource

class MyServerProtocol(WebSocketServerProtocol):
    def onConnect(self, request):
        stuff...
    def onOpen(self):
        stuff...
    def onMessage(self,payload):
        stuff...


factory = WebSocketServerFactory(u"ws://0.0.0.0:8080")
factory.protocol = MyServerProtocol
resource = WebSocketResource(factory)

root = File(".")
root.putChild(b"ws", resource)
site = Site(root)

reactor.listenTCP(8080, site)
reactor.run()

客户端的连接部分如下:

var wsuri;
var hostname = window.document.location.hostname;
wsuri = "ws://" + hostname + ":8080/ws";

if ("WebSocket" in window) {
    sock = new WebSocket(wsuri);
} else if ("MozWebSocket" in window) {
    sock = new MozWebSocket(wsuri);
} else {
    log("Browser does not support WebSocket!");
    window.location = "http://autobahn.ws/unsupportedbrowser";
}

openshift配置如下:

使用app.py在端口8080上侦听1个pod 没有启用 我有一个非tls路线8080> 8080。

Firefox在控制台中提供以下消息:

Firefox can’t establish a connection to the server at ws://openshiftprovidedurl.net:8080/ws.

当我使用wscat连接websocket时。

wscat -c ws://openshiftprovidedurl.net/ws

我收到以下错误:

error: Error: unexpected server response (400)

并且openshift中的应用程序登录显示以下内容:

2018-04-03 01:14:24+0000 [-] failing WebSocket opening handshake ('missing port in HTTP Host header 'openshiftprovidedurl.net' and server runs on non-standard port 8080 (wss = False)')
2018-04-03 01:14:24+0000 [-] dropping connection to peer tcp4:173.21.2.1:38940 with abort=False: missing port in HTTP Host header 'openshiftprovidedurl.net' and server runs on non-standard port 8080 (wss = False)
2018-04-03 01:14:24+0000 [-] WebSocket connection closed: connection was closed uncleanly (missing port in HTTP Host header 'openshiftprovidedurl.net' and server runs on non-standard port 8080 (wss = False))

任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:1)

格雷厄姆·杜普顿敲了敲头,我修改了代码

factory = WebSocketServerFactory(u"ws://0.0.0.0:8080")

factory = WebSocketServerFactory(u"ws://0.0.0.0:8080", externalPort=80)

它纠正了这个问题。我必须修改我的索引以指向正确的websocket但我现在能够连接。

谢谢!

答案 1 :(得分:0)

根据autobahn-python的源代码,您只能在2种情况下获取该消息。

以下是implementation

if not ((self.factory.isSecure and self.factory.externalPort == 443) or (not self.factory.isSecure and self.factory.externalPort == 80)):
                    return self.failHandshake("missing port in HTTP Host header '%s' and server runs on non-standard port %d (wss = %s)" % (str(self.http_request_host), self.factory.externalPort, self.factory.isSecure))

因为我认为您的服务器正在使用Deployment + Service(可能还有Ingress),您可以将服务器绑定到端口80而不是8080,并在服务中设置该端口在Ingress,如果你正在使用它们。