Twisted web server and Autobahn WebSocket at the same time, same port

1.2k views Asked by At

I have a server that listens for WebSocket connections on port 80, using Twisted and Autobahn. I want to have it also serve static HTML pages, for when the client doesn't want to use a WebSocket. Is it possible to do both things at the same time, using Twisted and Autobahn?

2

There are 2 answers

0
oberstet On BEST ANSWER

Sure, have a look here and here. You can run Twisted Web and add a Autobahn based WebSocket Twisted Web resource on a path. You can add any number of Twisted Web resources into your resource tree.

Briefly the technique is to start your WebSocketServerFactory manually by invoking startFactory(), then wrap it within a autobahn.twisted.resource.WebSocketResource resource, which you can then register with putChild anywhere within a Twisted Web hierarchy.

4
Greg On

I think you have to add haproxy to the mix. If you want to just use twisted and autobahn then I don't think you can share the port. Having said that, I've got both my websockets and web server listening on the same external port. I had to use haproxy to do the trick, though...haproxy handle the inbound connection, then distributes the connection based upon things it pulls from its environment. Every environment is different. Basically, you get haproxy running, then make your web service and web socket listen on private, different ports. In my case I put my web socket server on 127.0.0.1:9000, and my web service on 127.0.0.1:8080. Then you create a haproxy.conf file for haproxy's configuration, in this example, something like:

global
    maxconn 100
    mode http
frontend myfrontend
    bind *:80
    acl is_websocket hdr(Upgrade) -i WebSocket
    use_backend ws if is_websocket
    default_backend mybackend
backend mybackend
     server s3 127.0.0.1:8080
backend ws
    timeout server 600s
    reqrep ^Host:\ .* \0:9000
    server ws1 127.0.0.1:9000

I had to remove a bunch of unrelated stuff from the haproxy.conf file, but this gets the idea across. It was important to me to have only one port visible from the outside instead of managing two.

haproxy is awesome ! -g