当前位置: 首页>>代码示例>>Python>>正文


Python uwsgi.websocket_handshake函数代码示例

本文整理汇总了Python中uwsgi.websocket_handshake函数的典型用法代码示例。如果您正苦于以下问题:Python websocket_handshake函数的具体用法?Python websocket_handshake怎么用?Python websocket_handshake使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了websocket_handshake函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: chat

def chat(request):
    try:
        room = Room.objects.get(pk=1)
    except:
        room = None

    uwsgi.websocket_handshake(request['HTTP_SEC_WEBSOCKET_KEY'], request.get('HTTP_ORIGIN', ''))
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    channel = r.pubsub()
    channel.subscribe(room.name)
    websocket_fd = uwsgi.connection_fd()
    redis_fd = channel.connection._sock.fileno()
    while True:
        ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0)
        if not ready[0]:
            uwsgi.websocket_recv_nb()
        for fd in ready[0]:
            if fd == websocket_fd:
                msg = uwsgi.websocket_recv_nb()
                if msg:
                    msg = json.loads(msg)
                    if msg['c'] == 'm':
                        first_msg = "%s: %s" % (msg['u'], msg['ms'])
                        second_msg = None
                        if first_msg and not second_msg:
                            r.publish(room.name, first_msg)
                        elif second_msg and first_msg:
                            r.publish(room.name, "%s <br> %s" % (first_msg, second_msg))
            elif fd == redis_fd:
                msg = channel.parse_response() 
                if msg[0] == 'message':
                    uwsgi.websocket_send("[%s] %s" % (time.time(), msg[2]))
开发者ID:GodsOfWeb,项目名称:django-chat,代码行数:32,代码来源:views.py

示例2: __call__

    def __call__(self, environ, start_response):
        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."""
                while True:
                    event.set()
                    select([fd], [], [])[0]
            self._select_greenlet = gevent.spawn(
                select_greenlet_runner,
                uwsgi.connection_fd(),
                self._event)

        return self.app(self)
开发者ID:Melvie,项目名称:BeerShed,代码行数:29,代码来源:async_gevent_uwsgi.py

示例3: application

def application(env, start_response):
    '''https://github.com/unbit/uwsgi/blob/master/tests/websockets_chat.py'''
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
    print 'websocket relay connecting...'
    r = redis.StrictRedis(host='redis', port=6379, db=0)
    channel = r.pubsub()
    channel.subscribe('broadcast')

    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:
                msg = uwsgi.websocket_recv_nb()
                if msg:
                    r.publish('incoming', msg)
            elif fd == redis_fd:
                msg = channel.parse_response()
                # only interested in user messages
                if msg[0] == 'message':
                    uwsgi.websocket_send(msg[-1])
开发者ID:awentzonline,项目名称:uwsgi-websocket-redis-relay,代码行数:27,代码来源:relay.py

示例4: connect

    def connect(self, app, request, user, host):
        # noinspection PyUnresolvedReferences
        import uwsgi
        import json

        uwsgi.websocket_handshake()

        self.open(app=app, request=request, user=user, host=host)
        try:
            while True:
                try:
                    msg = uwsgi.websocket_recv()
                except OSError:
                    raise SystemExit()

                msg = msg.decode()
                msg = json.loads(msg)
                if "action" in msg:
                    ws_request = Request(msg, environ=request.environ)
                    pipe = RequestPipe()
                    result = pipe.process(self, app, ws_request, user, host)
                    if isinstance(result, dict):
                        result.update({"ws": {"event": msg["action"]}})
                    if isinstance(result, (bytes, bytearray)):
                        uwsgi.websocket_send(result)
                    else:
                        uwsgi.websocket_send(
                            json.dumps(result, default=json_dumps_handler)
                            if isinstance(result, (list, dict))
                            else str(result)
                        )
                    self.tick(app=app, request=ws_request, user=user, host=host)
        finally:
            self.close(app=app, request=request, user=user, host=host)
开发者ID:verteen,项目名称:envi,代码行数:34,代码来源:classes.py

示例5: wsData

 def wsData(self):
     """Websocket redis hget"""
     uwsgi.websocket_handshake(self.environ['HTTP_SEC_WEBSOCKET_KEY'], self.environ.get('HTTP_ORIGIN', ''))
     codes = []
     while True:
         t = str(int(time.time()))
         legend = []
         data = []
         keys = sorted(self.r.keys("sum_*"))
         for code in codes:
             key = '_'.join(["sum", code])
             legend.append("")
             if self.r.hexists(key, t):
                 data.append(int(self.r.hget(key, t)))
             else:
                 data.append(0)
         for key in keys:
             code = key.split('_')[-1]
             if self.r.hexists(key, t) and code not in codes:
                 codes.append(code)
                 data.append(int(self.r.hget(key, t)))
                 legend.append(code)
         if not data:
             time.sleep(2)
             continue
         wsdata = {
             "data": data,
             "legend": legend
         }
         uwsgi.websocket_send(json.JSONEncoder().encode(wsdata))
         time.sleep(2)
开发者ID:bagel,项目名称:cluster,代码行数:31,代码来源:mon.py

示例6: connect

    def connect(self, app, request, user, host):
        import uwsgi
        uwsgi.websocket_handshake()
        self.open(app=app, request=request, user=user, host=host)
        try:
            while True:
                try:
                    msg = uwsgi.websocket_recv_nb()
                    if msg:
                        msg = msg.decode()
                        try:
                            msg = json.loads(msg, object_hook=json_loads_handler)
                        except ValueError:
                            msg = None

                        if msg:
                            self.process_request_from_browser(app, request, user, host, msg, uwsgi)
                    else:
                        for msg in self.messages:
                            uwsgi.websocket_send(json.dumps(msg, default=json_dumps_handler))
                    sleep(0.1)
                except OSError:
                    raise SystemExit()
        finally:
            self.close(app=app, request=request, user=user, host=host)
开发者ID:ayurjev,项目名称:envi,代码行数:25,代码来源:classes.py

示例7: init_container

def init_container():
    host = request.environ.get('HTTP_HOST', '')

    uwsgi.websocket_handshake()

    while True:
        req = uwsgi.websocket_recv()
        #print('REQ', req)
        req = json.loads(req)
        if req['state'] == 'done':
            break

        client_id = req.get('id')
        if not client_id:
            client_id = dc.add_new_client()

        client_id, queue_pos = dc.am_i_next(client_id)

        if queue_pos < 0:
            resp = do_init(req['browser'], req['url'], req['ts'], host)
        else:
            resp = {'queue': queue_pos, 'id': client_id}

        resp = json.dumps(resp)
        #print('RESP', resp)
        uwsgi.websocket_send(resp)

    print('ABORTING')
开发者ID:pombredanne,项目名称:netcapsule,代码行数:28,代码来源:main.py

示例8: websocket

def websocket():
    print('im in ws')
    env = request.environ
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    channel = r.pubsub()
    channel.subscribe('teste_ws')
    websocket_fd = uwsgi.connection_fd()
    redis_fd = channel.connection._sock.fileno()
    while True:
        print("here in the loop")
        # 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:
                msg = uwsgi.websocket_recv_nb()
                if msg:
                    r.publish('teste_ws', msg)
            elif fd == redis_fd:
                msg = channel.parse_response()
                # only interested in user messages
                if msg[0] == b'message':
                    uwsgi.websocket_send(msg[2])
开发者ID:ecostadaluz,项目名称:core,代码行数:26,代码来源:__init__.py

示例9: __call__

    def __call__(self, environ, start_response):
        uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))
        self.r = redis.StrictRedis(host=self.redis_host, port=self.redis_port, db=0)
        channel = self.r.pubsub()
        channel.subscribe(self.room)

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

        core_id = environ['uwsgi.core']
        self.setup(core_id)

        while True:
            ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0)
            if not ready[0]:
                uwsgi.websocket_recv_nb()
            for fd in ready[0]:
                if fd == websocket_fd:
                    try:
                        msg = uwsgi.websocket_recv_nb()
                    except IOError:
                        self.end(core_id)
                        return ""
                    if msg:
                        self.websocket(core_id, msg)
                elif fd == redis_fd:
                    msg = channel.parse_response()
                    if msg[0] == 'message':
                        uwsgi.websocket_send(msg[2])
开发者ID:awentzonline,项目名称:SLAK,代码行数:29,代码来源:tremolo.py

示例10: websocket_view

        def websocket_view(context, request):
            uwsgi.websocket_handshake()
            this = greenlet.getcurrent()
            this.has_message = False
            q_in = asyncio.Queue()
            q_out = asyncio.Queue()

            # make socket proxy
            if inspect.isclass(view):
                view_callable = view(context, request)
            else:
                view_callable = view
            ws = UWSGIWebsocket(this, q_in, q_out)

            # start monitoring websocket events
            asyncio.get_event_loop().add_reader(
                uwsgi.connection_fd(),
                uwsgi_recv_msg,
                this
            )

            # NOTE: don't use synchronize because we aren't waiting
            # for this future, instead we are using the reader to return
            # to the child greenlet.

            future = asyncio.Future()
            asyncio.async(
                run_in_greenlet(this, future, view_callable, ws)
            )

            # switch to open
            this.parent.switch()

            while True:
                if future.done():
                    if future.exception() is not None:
                        raise future.exception()
                    raise WebsocketClosed

                # message in
                if this.has_message:
                    this.has_message = False
                    try:
                        msg = uwsgi.websocket_recv_nb()
                    except OSError:
                        msg = None

                    if msg or msg is None:
                        q_in.put_nowait(msg)

                # message out
                if not q_out.empty():
                    msg = q_out.get_nowait()
                    try:
                        uwsgi.websocket_send(msg)
                    except OSError:
                        q_in.put_nowait(None)

                this.parent.switch()
开发者ID:circlingthesun,项目名称:aiopyramid,代码行数:59,代码来源:uwsgi.py

示例11: application

def application(env, start_response):
    if env['PATH_INFO'] == "/ws/":
        uwsgi.websocket_handshake(env.get('HTTP_SEC_WEBSOCKET_KEY', ''), env.get('HTTP_ORIGIN', ''))
        while True:
            msg = uwsgi.websocket_recv()
            uwsgi.websocket_send(msg)
    else:
        return get_wsgi_application()(env, start_response)
开发者ID:bmelton,项目名称:SupportClassrooms,代码行数:8,代码来源:wsgi.py

示例12: application

def application(e, sr):
    if e['PATH_INFO'] == '/phys':
        uwsgi.websocket_handshake()

        w = World()
        me = Box('box0', w, 1000, 250, -1000, 250, 0)
        box1 = Box('box1', w, 20, 50, -1000, 250, 0)
        box2 = Box('box2', w, 20, 50, -1500, 350, 0)
        box3 = Box('box3', w, 20, 50, -1500, 450, 0)
        box4 = Box('box4', w, 200, 150, -1500, 550, 0)

        ramp = Ramp('ramp0', w, 400, 0, 100, 7000, 10, 400)

        print "BOX DRAWING COMPLETE"

        gevent.spawn(physic_engine, w)
        ufd = uwsgi.connection_fd()
        while True:

            ready = gevent.select.select([ufd, w.redis_fd], [], [], timeout=4.0)

            if not ready[0]:
                uwsgi.websocket_recv_nb()

            for fd in ready[0]:
                if fd == ufd:
                    try:
                        msg = uwsgi.websocket_recv_nb()
                        if msg == 'fw':
                            orientation = me.body.getOrientation()
                            v = Vector3(0, 0, 5000).rotate(orientation.getAxis(), orientation.getAngle())
                            me.body.activate(True)
                            me.body.applyCentralImpulse( v )
                        elif msg == 'bw':
                            orientation = me.body.getOrientation()
                            v = Vector3(0, 0, -5000).rotate(orientation.getAxis(), orientation.getAngle())
                            me.body.activate(True)
                            me.body.applyCentralImpulse( v )
                        elif msg == 'rl':
			    orientation = me.body.getOrientation()
                            v = Vector3(0, 2000000, 0).rotate(orientation.getAxis(), orientation.getAngle())
                            me.body.activate(True)
                            me.body.applyTorqueImpulse( v )
                        elif msg == 'rr':
			    orientation = me.body.getOrientation()
                            v = Vector3(0, -2000000, 0).rotate(orientation.getAxis(), orientation.getAngle())
                            me.body.activate(True)
                            me.body.applyTorqueImpulse( v )
                            #me.body.applyForce( Vector3(0, 0, 10000), Vector3(-200, 0, 0))
                            #me.body.applyForce( Vector3(0, 0, -10000), Vector3(200, 0, 0))
                    except IOError:
                        import sys
                        print sys.exc_info()
                        return [""]
                elif fd == w.redis_fd:
                    msg = w.channel.parse_response()
                    if msg[0] == 'message':
                        uwsgi.websocket_send(msg[2])
开发者ID:20tab,项目名称:robotab,代码行数:58,代码来源:bullphys.py

示例13: application

def application(env, sr):

    ws_scheme = "ws"
    if "HTTPS" in env or env["wsgi.url_scheme"] == "https":
        ws_scheme = "wss"

    if env["PATH_INFO"] == "/":
        sr("200 OK", [("Content-Type", "text/html")])
        return """
    <html>
      <head>
          <script language="Javascript">
            var s = new WebSocket("%s://%s/foobar/");
            s.onopen = function() {
              alert("connected !!!");
              s.send("ciao");
            };
            s.onmessage = function(e) {
		var bb = document.getElementById('blackboard')
		var html = bb.innerHTML;
		bb.innerHTML = html + '<br/>' + e.data;
            };

	    s.onerror = function(e) {
			alert(e);
		}

	s.onclose = function(e) {
		alert("connection closed");
	}

            function invia() {
              var value = document.getElementById('testo').value;
              s.send(value);
            }
          </script>
     </head>
    <body>
        <h1>WebSocket</h1>
        <input type="text" id="testo"/>
        <input type="button" value="invia" onClick="invia();"/>
	<div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
	</div>
    </body>
    </html>
        """ % (
            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))
开发者ID:rascalmicro,项目名称:uwsgi,代码行数:55,代码来源:websockets_echo.py

示例14: application

def application(env, sr):

    ws_scheme = 'ws'
    if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https':
        ws_scheme = 'wss'

    if env['PATH_INFO'] == '/':
        sr('200 OK', [('Content-Type','text/html')])
        return """
    <html>
      <head>
          <script language="Javascript">
            var s = new WebSocket("%s://%s/foobar/");
            s.onopen = function() {
              alert("connected !!!");
              s.send("ciao");
            };
            s.onmessage = function(e) {
		var bb = document.getElementById('blackboard')
		var html = bb.innerHTML;
		bb.innerHTML = html + '<br/>' + e.data;
            };

	    s.onerror = function(e) {
			alert(e);
		}

	s.onclose = function(e) {
		alert("connection closed");
	}

            function invia() {
              var value = document.getElementById('testo').value;
              s.send(value);
            }
          </script>
     </head>
    <body>
        <h1>WebSocket</h1>
        <input type="text" id="testo"/>
        <input type="button" value="invia" onClick="invia();"/>
	<div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
	</div>
    </body>
    </html>
        """ % (ws_scheme, env['HTTP_HOST'])
    elif env['PATH_INFO'] == '/foobar/':
	uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
        print "websockets..."
	uwsgi.websocket_channel_join('room001')
        while True:
            msg = uwsgi.websocket_recv()
            print len(msg)
            #uwsgi.websocket_send("hello %s = %s" % (time.time(), msg)) 
            uwsgi.channel_send('room001', "channel %s = %s" % (time.time(), msg))
开发者ID:hfeeki,项目名称:uwsgi,代码行数:55,代码来源:websockets.py

示例15: application

def application(env, sr):
    """The main entry
    """
    # Get websocket scheme
    wsScheme = 'ws'
    if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https':
        wsScheme = 'wss'
    # The path info
    if env['PATH_INFO'] == '/':
        sr('200 OK', [ ('Content-Type', 'text/html' ) ])
        return """
    <html>
      <head>
          <script language="Javascript">
            var s = new WebSocket("%s://%s/foobar/");
            s.onopen = function() {
              alert("connected !!!");
              s.send("ciao");
            };
            s.onmessage = function(e) {
        var bb = document.getElementById('blackboard')
        var html = bb.innerHTML;
        bb.innerHTML = html + '<br/>' + e.data;
            };
        s.onerror = function(e) {
            alert(e);
        }
    s.onclose = function(e) {
        alert("connection closed");
    }
            function invia() {
              var value = document.getElementById('testo').value;
              s.send(value);
            }
          </script>
     </head>
    <body>
        <h1>WebSocket</h1>
        <input type="text" id="testo"/>
        <input type="button" value="invia" onClick="invia();"/>
    <div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
    </div>
    </body>
    </html>
        """ % (wsScheme, env['HTTP_HOST'])

    elif env['PATH_INFO'] == '/foobar/':
        uwsgi.websocket_handshake()
        print 'Start a web socket connection'
        while True:
            msg = uwsgi.websocket_recv()
            uwsgi.websocket_send("Server receive [%s] %s" % (time.time(), msg))
        print 'Close a web socket connection'
开发者ID:lipixun,项目名称:pytest,代码行数:53,代码来源:uwsgiserver.py


注:本文中的uwsgi.websocket_handshake函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。