Combining websockets and WSGI in a python app

前端 未结 2 1977
逝去的感伤
逝去的感伤 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)
    

提交回复
热议问题