Combining websockets and WSGI in a python app

前端 未结 2 1961
逝去的感伤
逝去的感伤 2020-12-28 09:16

I\'m working on a scientific experiment where about two dozen test persons play a turn-based game with/against each other. Right now, it\'s a Python web app with a WSGI inte

相关标签:
2条回答
  • 2020-12-28 09:55

    but I'm not sure about the architecture for mixing WSGI and websockets

    I made it

    use WSocket

    Simple WSGI HTTP + Websocket Server, Framework, Middleware And App.

    Includes

    • Server(WSGI) included - works with any WSGI framework
    • Middleware - adds Websocket support for any WSGI framework
    • Framework - simple Websocket WSGI web application framework
    • App - Event based app for Websocket communication When external server used, some clients like Firefox requires http 1.1 Server. for Middleware, Framework, App
    • Handler - adds Websocket support to wsgiref(python builtin WSGI server)
    • Client -Coming soon...

    Common Features

    • only single file less than 1000 lines
    • websocket sub protocol supported
    • websocket message compression supported (works if client asks)
    • receive and send pong and ping messages(with automatic pong sender)
    • receive and send binary or text messages
    • works for messages with or without mask
    • closing messages supported
    • auto and manual close

    example using bottle web framework and WSocket middleware

    from bottle import request, Bottle
    from wsocket import WSocketApp, WebSocketError, logger, run
    from time import sleep
    
    logger.setLevel(10)  # for debugging
    
    bottle = Bottle()
    app = WSocketApp(bottle)
    # app = WSocketApp(bottle, "WAMP")
    
    @bottle.route("/")
    def handle_websocket():
        wsock = request.environ.get("wsgi.websocket")
        if not wsock:
            return "Hello World!"
    
        while True:
            try:
                message = wsock.receive()
                if message != None:
                    print("participator : " + message)
                    
                wsock.send("you : "+message)
                sleep(2)
                wsock.send("you : "+message)
                
            except WebSocketError:
                break
                
    run(app)
    
    0 讨论(0)
  • 2020-12-28 10:19

    Here is an example that does what you want:

    • https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/websocket/echo_wsgi

    It runs a WSGI web app (Flask-based in this case, but can be anything WSGI conforming) plus a WebSocket server under 1 server and 1 port.

    You can send WS messages from within Web handlers. Autobahn also provides PubSub on top of WebSocket, which greatly simplifies the sending of notifications (via WampServerProtocol.dispatch) like in your case.

    • http://autobahn.ws/python

    Disclosure: I am author of Autobahn and work for Tavendo.

    0 讨论(0)
提交回复
热议问题