예제 #1
0
파일: classes.py 프로젝트: verteen/envi
    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)
    def handle_ws(self, env):
        # complete the handshake
        uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'],
                                  env.get('HTTP_ORIGIN', ''))

        print('WS Connected: ' + env.get('QUERY_STRING', ''))

        ready = uwsgi.websocket_recv()

        print('Ready, Starting Audio Stream')

        self.start_proc()
        gevent.sleep(0.3)

        try:
            for buff in self.get_audio_buff():
                if not buff:
                    break

                uwsgi.websocket_send_binary(buff)
            print("stream end")

        except Exception as e:
            import traceback
            traceback.print_exc()

        finally:
            self.close()
            print('WS Disconnected')
예제 #3
0
def application(env, start_response):
    # complete the handshake
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'],
                              env.get('HTTP_ORIGIN', ''))
    while True:
        msg = uwsgi.websocket_recv()
        uwsgi.websocket_send(msg)
예제 #4
0
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')
예제 #5
0
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)
예제 #6
0
 def _recv_job(self):
     while True:
         try:
             payload = uwsgi.websocket_recv(request_context=self.ctx)
         except IOError:
             # connection was terminated
             self._exit()
         else:
             self.on_message(payload)
예제 #7
0
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))
예제 #8
0
파일: websockets.py 프로젝트: hfeeki/uwsgi
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))
예제 #9
0
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'
예제 #10
0
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))
 def wait(self):
     """Waits and returns received messages.
     If running in compatibility mode for older uWSGI versions,
     it also sends messages that have been queued by send().
     A return value of None means that connection was closed.
     This must be called repeatedly. For uWSGI < 2.1.x it must
     be called from the main greenlet."""
     while True:
         if self._req_ctx is not None:
             try:
                 msg = uwsgi.websocket_recv(request_context=self._req_ctx)
             except IOError:  # connection closed
                 return None
             return self._decode_received(msg)
         else:
             # we wake up at least every 3 seconds to let uWSGI
             # do its ping/ponging
             event_set = self._event.wait(timeout=3)
             if event_set:
                 self._event.clear()
                 # maybe there is something to send
                 msgs = []
                 while True:
                     try:
                         msgs.append(self._send_queue.get(block=False))
                     except gevent.queue.Empty:
                         break
                 for msg in msgs:
                     self._send(msg)
             # maybe there is something to receive, if not, at least
             # ensure uWSGI does its ping/ponging
             try:
                 msg = uwsgi.websocket_recv()
             except IOError:  # connection closed
                 self._select_greenlet.kill()
                 return None
             if msg:  # message available
                 return self._decode_received(msg)
예제 #12
0
def application(env, sr):
    if env['PATH_INFO'] == '/':
        ws_scheme = 'ws'
        if 'HTTPS' in env or env['wsgi.url_scheme'] == 'https':
            ws_scheme = 'wss'
        sr('200 OK', [('Content-Type', 'text/html')])
        host = env.get('HTTP_X_FORWARDED_HOST', env['HTTP_HOST'])
        return index_html_template % (ws_scheme, host)
    elif env['PATH_INFO'] == '/ws/':
        uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'],
                                  env.get('HTTP_ORIGIN', ''))
        while True:
            msg = uwsgi.websocket_recv()
            uwsgi.websocket_send(msg)
    else:
        sr('404 NOT FOUND', [('Content-Type', 'text/plain')])
        return 'Not found'
예제 #13
0
파일: classes.py 프로젝트: ayurjev/envi
    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()
                except OSError:
                    raise SystemExit()

                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)
        finally:
            self.close(app=app, request=request, user=user, host=host)
예제 #14
0
 def wait(self):
     """Waits and returns received messages.
     If running in compatibility mode for older uWSGI versions,
     it also sends messages that have been queued by send().
     A return value of None means that connection was closed.
     This must be called repeatedly. For uWSGI < 2.1.x it must
     be called from the main greenlet."""
     while True:
         if self._req_ctx is not None:
             try:
                 msg = uwsgi.websocket_recv(request_context=self._req_ctx)
             except IOError:  # connection closed
                 return None
             return self._decode_received(msg)
         else:
             # we wake up at least every 3 seconds to let uWSGI
             # do its ping/ponging
             event_set = self._event.wait(timeout=3)
             if event_set:
                 self._event.clear()
                 # maybe there is something to send
                 msgs = []
                 while True:
                     try:
                         msgs.append(self._send_queue.get(block=False))
                     except gevent.queue.Empty:
                         break
                 for msg in msgs:
                     self._send(msg)
             # maybe there is something to receive, if not, at least
             # ensure uWSGI does its ping/ponging
             try:
                 msg = uwsgi.websocket_recv_nb()
             except IOError:  # connection closed
                 self._select_greenlet.kill()
                 return None
             if msg:  # message available
                 return self._decode_received(msg)
예제 #15
0
    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()
                except OSError:
                    raise SystemExit()

                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)
        finally:
            self.close(app=app, request=request, user=user, host=host)
def face_search(request):
    """
    进行人脸识别登录
    :param request:
    :return:
    """
    import uwsgi
    uwsgi.websocket_handshake()
    # 设置开始时间,如果60秒没有识别,断开socket连接
    begin = datetime.datetime.now()
    while True:
        message = uwsgi.websocket_recv()
        print('人脸识别登录....................................................')
        # 判断是否超时
        if (datetime.datetime.now() - begin).seconds > 60:
            print('人脸识别超时......')
            uwsgi.websocket_send('202'.encode())
            break

        # 如果有消息
        if message:
            try:
                # 将字节转为字符串
                params = message.decode()

                # 分割接收到的数据 分割方式和前端商榷好为 :#:
                params_list = params.split(':#:')
                if len(params_list) == 2:
                    img_b64_data = params_list[0][(params_list[0]).find('base64,') + 7:]  # 截取图片base64编码
                    request_username = params_list[1]

                    # 将img_bin_data base64解码
                    img_bin_data = base64.b64decode(img_b64_data)
                    # 判断是否是图片,如果不是
                    if not imghdr.what(None, img_bin_data):
                        continue

                    # 将图片二进制转为image object
                    f = BytesIO()
                    f.write(img_bin_data)
                    img = InMemoryUploadedFile(f, None, 'username', None, len(img_bin_data), None, None)
                    # 进行人脸识别
                    name = exe_search(img)
                    print('username: '******'Unknow'):
                            continue

                        # 根据name获取用户user对象
                        username = name[0]
                        user = User.objects.filter(username=username)
                        if user.count() == 1:
                            if user[0].username == request_username:
                                # 将结果缓存到redis
                                red.setex(username+'_face_success', 200, 60*5)
                                uwsgi.websocket_send('200'.encode())  # 发送消息到客户端
                                time.sleep(0.1)
                                break
                            else:
                                uwsgi.websocket_send('203'.encode())  # 发送消息到客户端
                                time.sleep(0.1)
                                break
                    else:
                        # []
                        continue

            except Exception as e:
                logger.error(e)
                continue
예제 #17
0
def application(env, start_response):
    uwsgi.websocket_handshake(HTTP_SEC_WEBSOCKET_KEY, env.get('HTTP_ORIGIN', ''))
    while True:
        msg = uwsgi.websocket_recv()
        uwsgi.websocket_send(msg)
예제 #18
0
파일: wrapper.py 프로젝트: fossabot/beecell
 def websocket_recv(self):
     ''' '''
     return uwsgi.websocket_recv()
예제 #19
0
def application(environ, start_response):
    request_method = environ['REQUEST_METHOD']
    path_info = environ['PATH_INFO']
    query_string = environ['QUERY_STRING']
    resource = os.path.join(root, path_info.lstrip('/'))

    def http_headers(environ):
        return '\n'.join(
            '%s=%s' % (k, v) for k, v in environ.iteritems()
            if k.startswith("HTTP_")
        )

    if path_info == "/ws/echo":
        uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))

        msg = uwsgi.websocket_recv()
        uwsgi.websocket_send(json.dumps(
            {
                'headers': {
                    k: str(v) for k, v in environ.iteritems()
                    if k.startswith("HTTP_")
                },
                'message': msg
            },
            indent=True
        ))
        uwsgi.websocket_send(msg)
        return []

    if (path_info.startswith("http://") or path_info.startswith("https://") or request_method == "CONNECT"):
        if query_string == "auth":
            if "HTTP_PROXY_AUTHORIZATION" not in environ:
                return proxy_auth(start_response)

        return ok(start_response,
                  "Proxy request (%s):\n%s" % (request_method, http_headers(environ)),
                  'text/plain')

    if request_method != "GET":
        return bad(start_response, '{"result": "Invalid request"}')

    if path_info == "/echo":
        return ok(start_response,
                  http_headers(environ),
                  'text/plain')

    if path_info == "/__PORT__":
        return ok(start_response, environ["SERVER_PORT"], 'text/plain')

    if path_info == "/__IP__":
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('a.root-servers.net.', 0))
        server_ip, _ = s.getsockname()
        return ok(start_response, server_ip, 'text/plain')

    if os.path.exists(resource):
        if os.path.isfile(resource):
            return ok(start_response,
                      open(resource).read(),
                      *content_type_magic(resource))

        if os.path.isdir(resource):
            return ok(start_response,
                      '\n'.join(
                        '<p><a href="%(fn)s">%(fn)s</a></p>' % {'fn': fn}
                        for fn in os.listdir(resource)
                      ),
                      'text/html')

    return notfound(start_response)
예제 #20
0
파일: ws.py 프로젝트: smason/demo-ws
 def recv(self):
     return uwsgi.websocket_recv(request_context=self.request_context)
def change_face_recognition(request):
    """
    进行人脸识别更改
    :param request:
    :return:
    """
    # 设置开始时间,如果20秒没有识别,断开socket连接
    import uwsgi
    uwsgi.websocket_handshake()
    # 设置开始时间,如果60秒没有识别,断开socket连接
    begin = datetime.datetime.now()
    count = 0
    while True:
        message = uwsgi.websocket_recv()
        # 判断是否超时
        if (datetime.datetime.now() - begin).seconds > 60:
            print('人脸识别超时......')
            uwsgi.websocket_send('202'.encode())
            break

        # 如果有消息
        if message:
            try:
                # 将字节转为字符串
                params = message.decode()

                # 分割接收到的数据 分割方式和前端商榷好为 :#:
                params_list = params.split(':#:')
                if len(params_list) == 2:
                    img_b64_data = params_list[0][(params_list[0]).find('base64,')+7:]  # 截取图片base64编码
                    uuid_var = params_list[1]

                    # 将img_bin_data base64解码
                    img_bin_data = base64.b64decode(img_b64_data)
                    # 判断是否是图片,如果不是
                    if (not imghdr.what(None, img_bin_data)) or (not uuid_var):
                        continue

                    key = uuid_var + 'person'
                    # 判断是否已经识别成功
                    res = red.get(key)
                    if res:
                        uwsgi.websocket_send('200'.encode())
                        time.sleep(0.1)
                        break

                    # 将图片二进制转为image object
                    f = BytesIO()
                    f.write(img_bin_data)
                    img = InMemoryUploadedFile(f, None, 'username', None, len(img_bin_data), None, None)

                    # 先进行人脸检测 是否已存在 检测10次
                    if count < 10:

                        name = exe_search(img)
                        print('第%s次人脸检查' % count, name)

                        # 说明已经存在人脸
                        if name:
                            if name[0] != 'Unknow':
                                # 判断人脸和现在的是否一样 如果一样可以注册
                                if name[0] == request.user.username:
                                    # 注册:
                                    count = 10
                                    continue
                                # 别的账号已经用了这张脸
                                else:
                                    uwsgi.websocket_send('201'.encode())  # 发送消息到客户端
                                    break
                            else:
                                count += 1
                                continue
                        else:
                            count += 1
                            continue

                    # 进行人脸识别
                    person = find_face(img, 'username')

                    # 识别成功
                    if person.encoded_face:
                        if len(person.encoded_face) == 1:
                            # 对数据person进行缓存
                            encoded_face = [list(person.encoded_face[0])]
                            encoded_face = json.dumps(encoded_face)
                            red.setex(key, encoded_face, 60 * 5)
                            uwsgi.websocket_send('200'.encode())  # 发送消息到客户端
                            time.sleep(0.1)
                            break
                    else:
                        uwsgi.websocket_send('请保持镜头内有一张人脸'.encode())  # 发送消息到客户端
            except Exception as e:
                logger.error(e)
예제 #22
0
    if rlen <= 0:
        raise IOError("unable to receive data")
    return ffi.string(data[0:rlen])
uwsgi.recv = uwsgi_pypy_recv
    
"""
uwsgi.close(fd)
"""
uwsgi.close = lambda fd: lib.close(fd)

"""
uwsgi.disconnect()
"""
uwsgi.disconnect = lambda: lib.uwsgi_disconnect(uwsgi_pypy_current_wsgi_req())

"""
uwsgi.websocket_recv()
"""
def uwsgi_pypy_websocket_recv():
    wsgi_req = uwsgi_pypy_current_wsgi_req();
    ub = lib.uwsgi_websocket_recv(wsgi_req);
    if ub == ffi.NULL:
        raise IOError("unable to receive websocket message")
    ret = ffi.string(ub.buf, ub.pos)
    lib.uwsgi_buffer_destroy(ub)
    return ret
uwsgi.websocket_recv = uwsgi_pypy_websocket_recv

"""
uwsgi.websocket_recv_nb()
"""
예제 #23
0
 def _recv_job(self):
     while True:
         data = uwsgi.websocket_recv(request_context=self.ctx)
         self.on_data(data)
예제 #24
0
 def receive(self):
     """Receive message from websocket."""
     return uwsgi.websocket_recv()
예제 #25
0
def application(env, start_response):
	uwsgi.websocket_handshake(env["HTTP_SEC_WEBSOCKET_KEY"], env.get("HTTP_ORIGIN", ""))
	if (not uwsgi.cache_exists("chats")):
		uwsgi.cache_update("chats", "")
	if (not uwsgi.cache_exists("names")):
		uwsgi.cache_update("names", "")
	if (not uwsgi.cache_exists("roomNumbers")):
		uwsgi.cache_update("roomNumbers", "")
	#Static data for testing:
	if (uwsgi.cache_get("roomNumbers") == ""):
		uwsgi.cache_update("roomNumbers", uwsgi.cache_get("roomNumbers") + "".join([str(number) for number in [0, 10, 11, 12]]))
	if (not uwsgi.cache_exists("0")):
		uwsgi.cache_update("0", "1Reimu11Marisa22Rumia33Daiyousei44")
	if (not uwsgi.cache_exists("10")):
		uwsgi.cache_update("10", "2Cirno11Meiling22Koakuma33Patchouli44")
	if (not uwsgi.cache_exists("11")):
		uwsgi.cache_update("11", "3Sakuya11Remilia22Flandre33Letty44")
	if (not uwsgi.cache_exists("12")):
		uwsgi.cache_update("12", "0Chen11Alice22Lily33")
	playersMax = 4
	nameChat = ""
	roomsMax = 100
	roomNumberChat = -1
	while (True):
		msg = uwsgi.websocket_recv()
		msg_type = ""
		msg_data = ""
		if (msg and (msg != "")):
			msg_type = msg.split("")[0]
			msg_data = msg.split("")[1]
			print "Message: " + repr(msg) + "; " + "Type: " + repr(msg_type) + "; " + "Data: " + repr(msg_data)
		if (msg_type == "chat"):
			chats = uwsgi.cache_get("chats")
			chats += "" + msg_data + ""
			uwsgi.cache_update("chats", chats)
		if (msg_type == "close"):
			roomNumber = msg_data.split("")[0]
			name = msg_data.split("")[1]
			if (name):
				names = uwsgi.cache_get("names").split("")
				names.remove(name)
				uwsgi.cache_update("names", "".join(names))
				chats = uwsgi.cache_get("chats").split("")
				i = 0
				while (i < len(chats)):
					chat = chats[i].split("")
					if (name in chats[3:]):
						del chat[chat.index(name, 3)]
						chats[i] = "".join(chat)
			if (int(roomNumber) > -1):
				room = uwsgi.cache_get(roomNumber).split("")
				i = 1
				while (i < len(room)):
					if (name == room[i].split("")[0]):
						room[i] = ""
						room = "".join(room)
						uwsgi.cache_update(roomNumber, room)
						if (room[room.index(""):] == playersMax * ""):
							roomNumbers = uwsgi.cache_get("roomNumbers").split("")
							roomNumbers.remove(roomNumber)
							uwsgi.cache_update("roomNumbers", "".join(roomNumbers))
							uwsgi.cache_del(roomNumber)
						break
					i += 1
				print name + " disconnected."
			return [""]
		if (msg_type == "leave"):
			roomNumber = msg_data.split("")[0]
			name = msg_data.split("")[1]
			roomNumberChat = -1
			room = uwsgi.cache_get(roomNumber).split("")
			i = 1
			while (i < len(room)):
				if (name == room[i].split("")[0]):
					room[i] = ""
					room = "".join(room)
					uwsgi.cache_update(roomNumber, room)
					if (room[room.index(""):] == playersMax * ""):
						roomNumbers = uwsgi.cache_get("roomNumbers").split("")
						roomNumbers.remove(roomNumber)
						uwsgi.cache_update("roomNumbers", "".join(roomNumbers))
						uwsgi.cache_del(roomNumber)
					break
				i += 1
		if (msg_type == "join"):
			roomNumber = msg_data.split("")[0]
			name = msg_data.split("")[1]
			room = uwsgi.cache_get(roomNumber).split("")
			if (room[0] != "0"):
				uwsgi.websocket_send("false")
			else:
				i = 1
				while (i < len(room)):
					if ((room[i] == "") and (room[i] != name + "")):
						room[i] = name + room[i]
						room = "".join(room)
						uwsgi.cache_update(roomNumber, room)
						uwsgi.websocket_send(room)
						roomNumberChat = int(roomNumber)
						break
					i += 1
				else:
					uwsgi.websocket_send("false")
		if (msg_type == "name"):
			if (msg_data in uwsgi.cache_get("names").split("")):
				uwsgi.websocket_send("false")
			else:
				names = uwsgi.cache_get("names").split("")
				names.append(msg_data)
				uwsgi.cache_update("names", "".join(names))
				print msg_data + " connected."
				nameChat = msg_data
				uwsgi.websocket_send("true")
		if (msg_type == "roomCreate"):
			roomNumbers = uwsgi.cache_get("roomNumbers").split("")
			if (len(roomNumbers) == 100): #The cache is full
				uwsgi.websocket_send("false")
			roomNumbers = [int(number) for number in roomNumbers if number]
			#Not most efficient but easy way to find the lowest available room number:
			roomNumber = 0
			while (roomNumber in roomNumbers):
				roomNumber += 1
			roomNumbers.append(roomNumber)
			roomNumbers = sorted(roomNumbers)
			uwsgi.cache_update("roomNumbers", "".join([str(number) for number in roomNumbers]))
			roomNumberChat = roomNumber
			roomNumber = str(roomNumber)
			uwsgi.cache_update(roomNumber, "0" + "" + msg_data + "" + (playersMax - 1) * "")
			uwsgi.websocket_send(roomNumber)
		if (msg_type == "rooms"):
			rooms = []
			for number in uwsgi.cache_get("roomNumbers").split(""):
				if (number):
					rooms.append(number + "" + uwsgi.cache_get(number))
			uwsgi.websocket_send("".join(rooms))
		if (msg_type == "wait"):
			uwsgi.websocket_send(uwsgi.cache_get(msg_data.split("")[0]))
			room = uwsgi.cache_get(msg_data.split("")[0]).split("")
			room = [player.split("") for player in room]
			for player in room[1:]:
				if (not player[0]):
					break
			else:
				uwsgi.websocket_send("ready")
		chats = uwsgi.cache_get("chats")
		chats = chats.split("")
		i = 0
		while (i < len(chats)):
			chat = chats[i].split("")
			if (chat == [""]):
				i += 1
				continue
			if (nameChat not in chat[3:]):
				chat.append(nameChat)
				chats[i] = "".join(chat)
				if (roomNumberChat == int(chat[0])):
					uwsgi.websocket_send("chat" + chat[1] + "" + chat[2])
				names = uwsgi.cache_get("names").split("")
				namesChat = chat[3:]
				for name in names:
					if (name not in namesChat):
						break
				else:
					del chats[i]
			i += 1
		uwsgi.cache_update("chats", "".join(chats))
예제 #26
0
    def __call__(self, e, sr):
        if e['PATH_INFO'] == '/':
            sr('200 OK', [('Content-Type', 'text/html')])
            return [open('robotab_ws.html').read()]

        if e['PATH_INFO'] == '/robotab.js':
            sr('200 OK', [('Content-Type', 'application/javascript')])
            return [open('static/js/robotab.js').read()]

        if e['PATH_INFO'] == '/robotab':
            uwsgi.websocket_handshake()
            username, avatar = uwsgi.websocket_recv().split(':')
            try:
                robot_coordinates = self.spawn_iterator.next()
            except StopIteration:
                self.spawn_iterator = iter(self.spawn_points)
                robot_coordinates = self.spawn_iterator.next()

            uwsgi.websocket_send('posters:{}'.format(';'.join(self.posters)))

            for wall in self.walls:
                uwsgi.websocket_send('wall:{},{},{},{},{},{},{}'.format(*wall))

            player = Player(self, username, avatar, uwsgi.connection_fd(),
                            *robot_coordinates)

            if (self.started or self.finished
                    or len(self.players) > self.max_players
                    or len(self.waiting_players) > 0):
                print('{}:{}:{}:{}'.format(
                    self.started, self.finished,
                    len(self.players) > self.max_players,
                    len(self.waiting_players) > 0))

                self.waiting_players.append(player)
                uwsgi.websocket_send("arena:hey {}, wait for next game".format(
                    player.name))
                player.wait_for_game()
                self.waiting_players.remove(player)
            else:
                self.players[player.name] = player

            self.spawn_greenlets()

            for p in self.players.keys():
                self.players[p].update_gfx()

            while True:
                ready = gevent.select.select([player.fd, player.redis_fd], [],
                                             [],
                                             timeout=4.0)

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

                for fd in ready[0]:
                    if fd == player.fd:
                        try:
                            msg = uwsgi.websocket_recv_nb()
                        except IOError:
                            import sys
                            print sys.exc_info()
                            if player.name in self.players:
                                player.end('leaver')
                            return [""]
                        if msg and not self.finished:
                            self.msg_handler(player, msg)
                    elif fd == player.redis_fd:
                        msg = player.channel.parse_response()
                        if msg[0] == 'message':
                            uwsgi.websocket_send(msg[2])
예제 #27
0
    if rlen <= 0:
        raise IOError("unable to receive data")
    return ffi.string(data[0:rlen])
uwsgi.recv = uwsgi_pypy_recv
    
"""
uwsgi.close(fd)
"""
uwsgi.close = lambda fd: lib.close(fd)

"""
uwsgi.disconnect()
"""
uwsgi.disconnect = lambda: lib.uwsgi_disconnect(uwsgi_pypy_current_wsgi_req())

"""
uwsgi.websocket_recv()
"""
def uwsgi_pypy_websocket_recv():
    wsgi_req = uwsgi_pypy_current_wsgi_req();
    ub = lib.uwsgi_websocket_recv(wsgi_req);
    if ub == ffi.NULL:
        raise IOError("unable to receive websocket message")
    ret = ffi.string(ub.buf, ub.pos)
    lib.uwsgi_buffer_destroy(ub)
    return ret
uwsgi.websocket_recv = uwsgi_pypy_websocket_recv

"""
uwsgi.websocket_recv_nb()
"""
예제 #28
0
def application(env, sr):
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'],
                              env.get('HTTP_ORIGIN', ''))
    while True:
        data = json.loads(uwsgi.websocket_recv().decode('utf-8'))
        uwsgi.websocket_send_binary(maps.plot_from_data(data))
 def wait(self):
     print("reading")
     if self._sock is None:
         return uwsgi.websocket_recv()
     return self._sock.receive()
예제 #30
0
    def __call__(self, e, sr):
        if e['PATH_INFO'] == '/':
            sr('200 OK', [('Content-Type', 'text/html')])
            return [open('robotab_bullet.html').read()]

        if e['PATH_INFO'] == '/robotab_bullet.js':
            sr('200 OK', [('Content-Type', 'application/javascript')])
            return [open('static/js/robotab_bullet.js').read()]

        if e['PATH_INFO'] == '/robotab':
            uwsgi.websocket_handshake()
            username, avatar = uwsgi.websocket_recv().split(':')
            try:
                robot_coordinates = next(self.spawn_iterator)
            except StopIteration:
                self.spawn_iterator = iter(self.spawn_points)
                robot_coordinates = next(self.spawn_iterator)

            # uwsgi.websocket_send('posters:{}'.format(';'.join(self.posters)))

            for wall in self.walls_coordinates:
                uwsgi.websocket_send(
                    'wall:{},{},{},{},{},{},{}'.format(*wall))

            player = Player(self, username, avatar,
                            uwsgi.connection_fd(), *robot_coordinates)

            if(self.started or self.finished or
               len(self.players) > self.max_players or
               len(self.waiting_players) > 0):
                print('{}:{}:{}:{}'.format(
                    self.started, self.finished,
                    len(self.players) > self.max_players,
                    len(self.waiting_players) > 0))

                self.waiting_players.append(player)
                uwsgi.websocket_send(
                    "arena:hey {}, wait for next game".format(player.name))
                player.wait_for_game()
                self.waiting_players.remove(player)
            else:
                self.players[player.name] = player

            self.spawn_greenlets()

            player.update_gfx()

            for p in self.players.keys():
                uwsgi.websocket_send(self.players[p].last_msg)

            while True:
                ready = gevent.select.select(
                    [player.fd, player.redis_fd], [], [], timeout=4.0)

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

                for fd in ready[0]:
                    if fd == player.fd:
                        try:
                            msg = uwsgi.websocket_recv_nb()
                        except IOError:
                            import sys
                            print sys.exc_info()
                            if player.name in self.players:
                                player.end('leaver')
                            return [""]
                        if msg and not self.finished:
                            self.msg_handler(player, msg)
                    elif fd == player.redis_fd:
                        msg = player.channel.parse_response()
                        if msg[0] == 'message':
                            uwsgi.websocket_send(msg[2])
예제 #31
0
 def _recv_job(self):
     while True:
         data = uwsgi.websocket_recv(request_context=self.ctx)
         self.on_data(data)