Bottle + WebSocket

前端 未结 2 1563
难免孤独
难免孤独 2021-02-01 04:53

is it possible to host a normal Bottle application and a WebSocket one (example: https://github.com/defnull/bottle/blob/master/docs/async.rst) in the same application (same port

2条回答
  •  春和景丽
    2021-02-01 05:39

    It sure is.

    The server:

    #!/usr/bin/python
    
    import json
    from bottle import route, run, request, abort, Bottle ,static_file
    from pymongo import Connection
    from gevent import monkey; monkey.patch_all()
    from time import sleep
    
    app = Bottle()
    
    @app.route('/websocket')
    def handle_websocket():
        wsock = request.environ.get('wsgi.websocket')
        if not wsock:
            abort(400, 'Expected WebSocket request.')
        while True:
            try:
                message = wsock.receive()
                wsock.send("Your message was: %r" % message)
                sleep(3)
                wsock.send("Your message was: %r" % message)
            except WebSocketError:
                break
    
    @app.route('/')
    def send_html(filename):
        return static_file(filename, root='./static', mimetype='text/html')
    
    
    from gevent.pywsgi import WSGIServer
    from geventwebsocket import WebSocketHandler, WebSocketError
    
    host = "127.0.0.1"
    port = 8080
    
    server = WSGIServer((host, port), app,
                        handler_class=WebSocketHandler)
    print "access @ http://%s:%s/websocket.html" % (host,port)
    server.serve_forever()
    

    The html page that holds the javascript:

    
    
    
      
    
    
    
    
    

    A client:

    #!/usr/bin/python
    
    from websocket import create_connection
    ws = create_connection("ws://localhost:8080/websocket")
    print "Sending 'Hello, World'..."
    ws.send("Hello, World")
    print "Sent"
    print "Reeiving..."
    result =  ws.recv()
    print "Received '%s'" % result
    ws.close()
    

提交回复
热议问题