How to use the uwsgi.websocket_handshake function in uWSGI

To help you get started, we’ve selected a few uWSGI examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github unbit / uwsgi / tests / websockets.py View on Github external
var value = document.getElementById('testo').value;
              s.send(value);
            }
          
     
    
        <h1>WebSocket</h1>
        <input id="testo" type="text">
        <input value="invia" type="button">
        <div style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto" id="blackboard">
        </div>
    
    
        """ % (ws_scheme, env['HTTP_HOST'])
    elif env['PATH_INFO'] == '/foobar/':
        uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
        print "websockets..."
        while True:
            msg = uwsgi.websocket_recv_nb()
            if msg:
                queue.put(msg)
            else:
                try:
                    wait_read(uwsgi.connection_fd(), 0.1)
                except gevent.socket.timeout:
                    try:
                        msg = queue.get_nowait()
                        uwsgi.websocket_send(msg)
                    except Exception:
                        pass
    return ""
github unbit / uwsgi / tests / websockets_chat.py View on Github external
}
          
     
    
        <h1>WebSocket</h1>
        <input id="testo" type="text">
        <input value="invia" type="button">
        <div style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto" id="blackboard">
        </div>
    
    
        """ % (ws_scheme, env['HTTP_HOST'])
    elif env['PATH_INFO'] == '/favicon.ico':
        return ""
    elif env['PATH_INFO'] == '/foobar/':
        uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
        print "websockets..."
        r = redis.StrictRedis(host='localhost', port=6379, db=0)
        channel = r.pubsub()
        channel.subscribe('foobar')

        websocket_fd = uwsgi.connection_fd()
        redis_fd = channel.connection._sock.fileno()

        while True:
            # wait max 4 seconds to allow ping to be sent
            ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0)
            # send ping on timeout
            if not ready[0]:
                uwsgi.websocket_recv_nb()
            for fd in ready[0]:
                if fd == websocket_fd:
github unbit / uwsgi / tests / websockets_chat_asyncio.py View on Github external
}
          
     
    
        <h1>WebSocket</h1>
        <input id="testo" type="text">
        <input value="invia" type="button">
        <div style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto" id="blackboard">
        </div>
    
    
        """ % (ws_scheme, env['HTTP_HOST'])).encode()
    elif env['PATH_INFO'] == '/favicon.ico':
        return b""
    elif env['PATH_INFO'] == '/foobar/':
        uwsgi.websocket_handshake()
        print("websockets...")
        # a future for waiting for redis connection
        f = GreenFuture()
        asyncio.Task(redis_subscribe(f))
        # the result() method will switch greenlets if needed
        subscriber = f.result()

        # open another redis connection for publishing messages
        f0 = GreenFuture()
        t = asyncio.Task(redis_open(f0))
        connection = f0.result()

        myself = greenlet.getcurrent()
        myself.has_ws_msg = False
        # start monitoring websocket events
        asyncio.get_event_loop().add_reader(uwsgi.connection_fd(), ws_recv_msg, myself)
github unbit / uwsgi / tests / websockets_chat_2.py View on Github external
def start(self):
        uwsgi.websocket_handshake()
        self.ctx = uwsgi.request_context()

        ClientManager.add(self)

        self.jobs.extend([
            gevent.spawn(self._recv_job),
            gevent.spawn(self._send_job),
        ])

        for j in self.jobs:
            j.link(self._exit)

        gevent.joinall(self.jobs)
github unbit / uwsgi / tests / websockets_echo.py View on Github external
var value = document.getElementById('testo').value;
              s.send(value);
            }
          
     
    
        <h1>WebSocket</h1>
        <input id="testo" type="text">
        <input value="invia" type="button">
    <div style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto" id="blackboard">
    </div>
    
    
        """ % (ws_scheme, env['HTTP_HOST'])
    elif env['PATH_INFO'] == '/foobar/':
        uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
        print "websockets..."
        while True:
            msg = uwsgi.websocket_recv()
            uwsgi.websocket_send("[%s] %s" % (time.time(), msg))
github danidee10 / Chatire / websocket.py View on Github external
)
    channel = connection.channel()

    exchange = env['PATH_INFO'].replace('/', '')

    channel.exchange_declare(
        exchange=exchange, exchange_type='fanout'
    )

    # exclusive means the queue should be deleted once the connection is closed
    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue  # random queue name generated by RabbitMQ

    channel.queue_bind(exchange=exchange, queue=queue_name)

    uwsgi.websocket_handshake(
        env['HTTP_SEC_WEBSOCKET_KEY'],
        env.get('HTTP_ORIGIN', '')
    )

    def keepalive():
        """Keep the websocket connection alive (called every 30 seconds)."""
        print('PING/PONG...')
        try:
            uwsgi.websocket_recv_nb()
            connection.add_timeout(30, keepalive)
        except OSError as error:
            print(error)
            sys.exit(1) # Kill process and force uWSGI to Respawn

    keepalive()
github danidee10 / django-notifs / examples / websocket.py View on Github external
def application(env, start_response):
    """Setup the Websocket Server and read messages off the queue."""
    rabbit_mq_url = settings.NOTIFICATIONS_RABBIT_MQ_URL
    connection = pika.BlockingConnection(
        pika.connection.URLParameters(rabbit_mq_url)
    )
    channel = connection.channel()

    queue = env['PATH_INFO'].replace('/', '')
    
    channel.queue_declare(queue=queue)

    uwsgi.websocket_handshake(
        env['HTTP_SEC_WEBSOCKET_KEY'],
        env.get('HTTP_ORIGIN', '')
    )

    def keepalive():
        """Keep the websocket connection alive (called each minute)."""
        print('PING/PONG...')
        try:
            uwsgi.websocket_recv_nb()
            connection.add_timeout(30, keepalive)
        except OSError as error:
            print(error)
            sys.exit(1) # Kill process and force uWSGI to Respawn

    keepalive()
github miguelgrinberg / python-engineio / engineio / async_drivers / gevent_uwsgi.py View on Github external
def __call__(self, environ, start_response):
        self._sock = uwsgi.connection_fd()
        self.environ = environ

        uwsgi.websocket_handshake()

        self._req_ctx = None
        if hasattr(uwsgi, 'request_context'):
            # uWSGI >= 2.1.x with support for api access across-greenlets
            self._req_ctx = uwsgi.request_context()
        else:
            # use event and queue for sending messages
            from gevent.event import Event
            from gevent.queue import Queue
            from gevent.select import select
            self._event = Event()
            self._send_queue = Queue()

            # spawn a select greenlet
            def select_greenlet_runner(fd, event):
                """Sets event when data becomes available to read on fd."""
github jrief / django-websocket-redis / ws4redis / uwsgi_runserver.py View on Github external
def upgrade_websocket(self, environ, start_response):
        uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))
        return uWSGIWebsocket()