• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python uwsgi.websocket_send函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: send

 def send(self, msg):
     try:
         uwsgi.websocket_send(msg)
         return True
     except IOError:
         self.close()
         return False
开发者ID:djskl,项目名称:uwsgi-websocket,代码行数:7,代码来源:uwsgi_ws_server.py


示例2: 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


示例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: 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


示例5: serve_handler

 def serve_handler(self, handler, values):
     def invoke_handler(handler, sock):
         try:
             handler(sock, **values)
         finally:
             sock.close()
     th = Thread(target=invoke_handler, args=(handler, self,))
     th.setDaemon(True)
     th.start()
     try:
         fd = uwsgi.connection_fd()
         while not self.evt_close.is_set():
             uwsgi.wait_fd_read(fd, 0.3)
             uwsgi.suspend()
             _fd = uwsgi.ready_fd()
             msg = uwsgi.websocket.recv_nb()
             if msg:
                 self.q_recv.put(msg)
             try:
                 msg = self.q.get(True, 0.1)
                 if msg:
                     uwsgi.websocket_send(msg)
             except Empty:
                 pass
     finally:
         self.close()
         th.join()
     return []
开发者ID:smallfz,项目名称:flask-ws,代码行数:28,代码来源:wsuwsgi.py


示例6: 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


示例7: 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


示例8: request_method

def request_method(cmd, cursor):
    query_data = ImmutableMultiDict(json.loads(cmd['query']))
    post_data = json.dumps(cmd['data'])

    logging.info('websocket endpoint request: %s, %s, %s, %s, %s' % (
        '0.2',          # API version               - 0.1, 0.2, etc.
        cmd['verb'],    # HTTP method               - GET, POST, PATCH, DELETE
        cmd['uri'],     # selector                  - '/relation/widget/dependency_js'
        query_data,     # query string arguments    - including event.session id
        post_data))     # post data

    cursor.execute(
        """select status, message, response, mimetype
             from endpoint.request({version}, {verb}, {path}, {query}, {data});""".format(
                 version = cmd['version'],
                 verb = cmd['verb'],
                 path = cmd['uri'],
                 query = json.dumps(query_data).to_dict(flat=False),
                 data = post_data))

    result = cursor.fetchone()

    uwsgi.websocket_send('''{
        "method": "response",
        "request_id": "%s",
        "data": %s
    }''' % (cmd['request_id'], result.response))
开发者ID:aquametalabs,项目名称:aquameta,代码行数:27,代码来源:events.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: 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


示例11: 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


示例12: 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


示例13: 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


示例14: handle_db_notifications

def handle_db_notifications(conn):
    conn.poll()
    while conn.notifies:
        notify = conn.notifies.pop(0)
        uwsgi.websocket_send('''{
            "method": "event",
            "data": %s
        }''' % (json.dumps(notify.payload),))
开发者ID:aquametalabs,项目名称:aquameta,代码行数:8,代码来源:events.py


示例15: 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


示例16: 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


示例17: detach_method

def detach_method(cmd, cursor, env):
    session_id = cmd['session_id']
    if session_id is not None:
        cursor.execute('select event.session_detach(%s);', (session_id,))
        logging.info('session detached: %s (role: %s)' % (session_id, env['DB_USER']))

        uwsgi.websocket_send('''{
            "method": "response",
            "request_id": "%s",
            "data": "true"
        }''' % (cmd['request_id'],))
开发者ID:aquametalabs,项目名称:aquameta,代码行数:11,代码来源:events.py


示例18: 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


示例19: application

def application(env, start_response):
    # complete the handshake
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'],
                              env.get('HTTP_ORIGIN', ''))
    parse = parse_qs(env['QUERY_STRING'])
    print("parse")
    counter = 0
    while True:
        # msg = uwsgi.websocket_recv()
        uwsgi.websocket_send("msg %d" % counter)
        counter += 1
        time.sleep(5)
开发者ID:forilen,项目名称:websocket_demo,代码行数:12,代码来源:app.py


示例20: ws_downloads

def ws_downloads():
    uwsgi.websocket_handshake()
    while True:
        uwsgi.websocket_recv_nb() # for close()
        gevent.sleep(2)

        try:
            payload = json.dumps(rtorrent.downloads())
        except:
            payload = json.dumps({'error': "can't connect to rtorrent"})

        uwsgi.websocket_send(payload)
开发者ID:RossValler,项目名称:carson,代码行数:12,代码来源:carson.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python uwsgi.worker_id函数代码示例发布时间:2022-05-26
下一篇:
Python uwsgi.websocket_recv_nb函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap