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])
def send(self, msg): try: uwsgi.websocket_send(msg) return True except IOError: self.close() return False
def new_session(cursor): token = UUID(bytes=urandom(16)) cursor.execute( ''' insert into event.session (token, owner_id) values (%s, ( select r.id from meta.role r where r.name = session_user --pg magic name, not referring to event.session limit 1 )) returning id ''', (str(token), )) uwsgi.websocket_send('''{ "method": "set_token", "args": { "token": "%s" } }''' % (token, )) session_id = cursor.fetchone().id return session_id
def application(env, start_response): # complete the handshake uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) r = redis.StrictRedis(host='redis-gandamu', port=6379, db=0) channel = r.pubsub() channel.subscribe('portfolio') websocket_fd = uwsgi.connection_fd() redis_fd = channel.connection._sock.fileno() while True: uwsgi.wait_fd_read(websocket_fd, 3) uwsgi.wait_fd_read(redis_fd) uwsgi.suspend() fd = uwsgi.ready_fd() if fd > -1: if fd == websocket_fd: msg = uwsgi.websocket_recv_nb() if msg: r.publish('portfolio', msg) elif fd == redis_fd: msg = channel.parse_response() # only interested in user messages t = 'message' if sys.version_info[0] > 2: t = b'message' if msg[0] == t: json = msg[2].decode('utf-8') uwsgi.websocket_send("%s" % json) # uwsgi.websocket_send("[%s] %s" % (time.time(), msg)) else: # on timeout call websocket_recv_nb again to manage ping/pong msg = uwsgi.websocket_recv_nb() if msg: r.publish('portfolio', msg)
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 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)
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)
def __call__(self, environ, start_response): uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', '')) print "websockets..." 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])
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')
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]))
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))
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)
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])
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))
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 []
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)
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])
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 WebsocketClosed from 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 UWSGIWebsocketMapper.use_str: with suppress(Exception): print('howdy') msg = bytes.decode(msg) 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()
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()
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), ))
def received_message(self, m): """Push upstream messages to downstream.""" # TODO: No support for binary messages m = str(m) logger.debug("Incoming upstream WS: %s", m) uwsgi.websocket_send(m) logger.debug("Send ok")
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)
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),))
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])
def __notice_user(redis_pubsub, flag): """通知用户消息""" while not flag.is_return: messages = redis_pubsub.listen() logger.error('收到了redis通道消息!') for msg in messages: logger.error('收到了消息{}!'.format(msg['type'])) if msg and msg['type'] == 'message': uwsgi.websocket_send(msg['data'])
def handle_send_event(self, client, send_event, send_queue): try: while True: data = send_queue.get_nowait() uwsgi.websocket_send(data) except Empty: send_event.clear() except IOError: client.connected = False
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 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'],))
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'
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'], ))
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 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)
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)
def attach_method(cmd, cursor, db_connection, env): session_id = cmd['session_id'] if session_id is not None: cursor.execute('select event.session_attach(%s);', (session_id,)) logging.info('session attached: %s (role: %s)' % (session_id, env['DB_USER'])) handle_db_notifications(db_connection) uwsgi.websocket_send('''{ "method": "response", "request_id": "%s", "data": "true" }''' % (cmd['request_id'],))
def attach_method(cmd, cursor, db_connection, env): session_id = cmd['session_id'] if session_id is not None: cursor.execute('select event.session_attach(%s);', (session_id, )) logging.info('session attached: %s (role: %s)' % (session_id, env['DB_USER'])) handle_db_notifications(db_connection) uwsgi.websocket_send('''{ "method": "response", "request_id": "%s", "data": "true" }''' % (cmd['request_id'], ))
def process_request_from_browser(self, app, request, user, host, msg, uwsgi): 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)
def process_request_from_browser(self, app, request, user, host, msg, uwsgi): 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)
def wsSubData(self): """Websocket subscribe redis pubsub""" uwsgi.websocket_handshake(self.environ['HTTP_SEC_WEBSOCKET_KEY'], self.environ.get('HTTP_ORIGIN', '')) channel = self.r.pubsub() channel.subscribe(self.channel) channel.parse_response() while True: try: wsdata = channel.parse_response()[2] except: time.sleep(1) wsdata = '' channel.subscribe(self.channel) channel.parse_response() uwsgi.websocket_send(wsdata)
def handle_request(r, msg): """Handle request for more messages received from websocket.""" request = json.loads(msg) first = int(request["first_id"]) last = int(request["last_id"]) # Don't fetch more than 50 messages at once: if (last > 0 and (last - 50 > first)) or (last < 0): first = last - 50 pickled_messages = r.lrange(REDIS_MESSAGES_KEY, first, last) messages = [] for pickled_message in pickled_messages: message = pickle.loads(pickled_message) messages.append(message) uwsgi.websocket_send(encode_messages(messages))
def application(env, sr): if env['PATH_INFO'] == '/': uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) describe = json.dumps({ 'describe': { 'stream': { 'timestamp': {'label': "Server Timestamp", 'units': "s"} } } }) uwsgi.websocket_send(describe.encode('utf-8')) while True: message = json.dumps({'timestamp': time.time()}) uwsgi.websocket_send(message.encode('utf-8')) yield uwsgi.async_sleep(1)
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'
def application(env, start_response): """Setup the Websocket Server and Read Messages Off the Queue""" connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() # exchange is the uri 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='') 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 websockets connection alive (called every 30 seconds).""" print('PING/PONG...') # noinspection PyShadowingNames try: msg = uwsgi.websocket_recv_nb() # print(msg.decode("utf-8")) connection.add_timeout(30, keepalive) except OSError as error: connection.close() print(error) sys.exit(0) # Kill process and force uWSGI to Respawn keepalive() while True: for method_frame, _, body in channel.consume(queue_name): try: uwsgi.websocket_send(body) except OSError as error: print(error) sys.exit(0) # Force uWSGI to Respawn else: # acknowledge the message channel.basic_ack(method_frame.delivery_tag)
def ws(env): uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) e = Event() events.add(e) try: while True: try: uwsgi.websocket_recv_nb() except OSError: break yield e.wait() if e.event(): assets = json.dumps(['boo', 'foo']) uwsgi.websocket_send(assets) finally: events.remove(e) e.close()
def main_loop(self): while self.state == ClientState.started: self.event.wait(3.0) try: message = uwsgi.websocket_recv_nb() except IOError: if self.state == ClientState.started: self.state = ClientState.suspended break if message: self.client_recv_queue.put_nowait(message) # push client messages to client try: message = self.client_send_queue.get(block=False) uwsgi.websocket_send(message) except gevent.queue.Empty: # no more messages, so we can clear the event self.event.clear()
def server(self, server): if not server: raise ValueError('server instance required.') def recv(server, sock): while not sock.evt_open.is_set(): time.sleep(0.05) if hasattr(server, 'on_open'): server.on_open(self) try: fd = uwsgi.connection_fd() while not sock.evt_close.is_set(): uwsgi.wait_fd_read(fd, 1.0) uwsgi.suspend() _fd = uwsgi.ready_fd() msg = uwsgi.websocket_recv_nb() if msg: frame = (1, OP_TEXT, msg) server.on_message(sock, frame) finally: sock.evt_close.set() th = None if hasattr(server, 'on_message'): th = Thread(target=recv, args=(server, self,)) th.setDaemon(True) th.start() #yield self._frame(True, OP_PING, '') # uwsgi.websocket_send('') self.evt_open.set() try: while not self.evt_close.is_set(): try: msg = self.q.get(True, 0.1) if msg: uwsgi.websocket_send(msg) except Empty: pass finally: sock.evt_close.set() if hasattr(server, 'on_close'): server.on_close(self) if th: th.join() return []
def link_view(request): if request_api.is_login(request): # 获取当前登录的用户 user = request_api.get_user(request) conn, pubsub = __register_connect(user['id']) uwsgi.websocket_handshake() # 发送所有用户未阅读的警报 alarm_dicts = __get_unread_alarm_dicts(user) for alarm_dict in alarm_dicts: uwsgi.websocket_send(json.dumps(alarm_dict).encode('utf-8')) flag = ReturnFlag() # 创建协程 gevent.joinall([ gevent.spawn(__check_live, conn=conn, flag=flag), gevent.spawn(__notice_user, redis_pubsub=pubsub, flag=flag), ])
def application(env, start_response): connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() exchange = env['PATH_INFO'].replace('/', '') channel.exchange_declare(exchange=exchange, exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange=exchange, queue=queue_name) uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) def keepalive(): print('PING/PONG...') try: uwsgi.websocket_recv_nb() connection.call_later(30, keepalive) except OSError as error: connection.close() print(error) sys.exit(1) keepalive() while True: for method_frame, _, body in channel.consume(queue_name): try: uwsgi.websocket_send(body) except OSError as error: print(error) sys.exit(1) else: channel.basic_ack(method_frame.delivery_tag)
def application(env, start_response): """웹소켓 서버 세팅, 메세지큐 consume""" params = pika.URLParameters(AMQP_URL) connection = pika.BlockingConnection(params) channel = connection.channel() exchange = env['PATH_INFO'].replace('/', '') channel.exchange_declare(exchange=exchange, exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue 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.call_later(30, keepalive) except OSError as error: print(error) sys.exit(1) # Kill process and force uWSGI to Respawn keepalive() while True: for method_frame, _, body in channel.consume(queue_name): try: uwsgi.websocket_send(body) except OSError as error: print(error) sys.exit(1) # Force uWSGI to Respawn else: # acknowledge the message channel.basic_ack(method_frame.delivery_tag)
def application(e, sr): if e['PATH_INFO'] == '/phys': uwsgi.websocket_handshake() w = World() me = Box('box0', w, 900, 200) me.set_pos(0, 1150, 0) box1 = Box('box1', w, 20, 50) box1.set_pos(0, 250, 0) box2 = Box('box2', w, 20, 50) box2.set_pos(0, 350, 0) box3 = Box('box3', w, 20, 50) box3.set_pos(0, 450, 0) box4 = Box('box4', w, 200, 150) box4.set_pos(0, 550, 0) 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': me.body.addForce((0, 250, 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])
def _start_websocket(): """ This is the most important piece of the code. It's the only one that is allowed to use the uwsgi websocket api. It deals with receiving: - spawn a _listen greenlet _ when notified that the websocket fd is ready, it will fetch the message, and push it to the right handler and writing: - spawns a handler whenever necessary - when notified that a handler wants to writes, does the writing :return: """ assert request.headers.get('Upgrade') == "websocket", "/websockets is only available for websocket protocol" assert uwsgi is not None, "You must run your app using uwsgi if you want to use the /websockets route" env = request.headers.environ uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) # engage in websocket _websocket_handlers['_websocket_listen'] = spawn(_listen, uwsgi.connection_fd()) # Spawn greenlet that will listen to fd while True: ready = wait([_websocket_send_event, _websocket_recv_event], None, 1) # wait for events if ready: # an event was set if ready[0] == _websocket_recv_event: try: msg = uwsgi.websocket_recv_nb() except IOError: _kill_all() return if msg: json_msg = json.loads(msg) handler = _websocket_handlers[json_msg['namespace']] handler.go(json_msg) _websocket_recv_event.clear() elif ready[0] == _websocket_send_event: # One or more handlers requested a message to be sent while True: try: msg = _websocket_send_queue.get_nowait() except Empty: break uwsgi.websocket_send(json.dumps(msg)) _websocket_send_event.clear()
def application(env, start_response): parse = parse_qs(env['QUERY_STRING']) if 'uid' not in parse: print('Connection error: uid not found') return '' uid = parse['uid'][0] uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) print('Connection to websocket %s', uid) channel = rd.pubsub() channel.subscribe(uid) print('Subscribe to channel %s', uid) ws_fd = uwsgi.connection_fd() rd_fd = channel.connection._sock.fileno() while True: # wait max 4 seconds to allow ping to be sent ready = select.select([ws_fd, rd_fd], [], [], 4.0) # send ping on timeout if not ready[0]: uwsgi.websocket_recv_nb() for fd in ready[0]: if fd == ws_fd: try: msg = uwsgi.websocket_recv_nb() if msg: print('Pub msg %s', msg) rd.publish(uid, msg) except IOError: print('Websocket Closed: %s', uid) return '' elif fd == rd_fd: msg = channel.parse_response() # only interested in user messages if msg[0] == 'message': print('Send msg %s', msg[2]) uwsgi.websocket_send(msg[2])
def wsSubData_nb(self): """Websocket subscribe redis pubsub nonbolocking. Keepalive websocket connection with client.""" uwsgi.websocket_handshake(self.environ['HTTP_SEC_WEBSOCKET_KEY'], self.environ.get('HTTP_ORIGIN', '')) channel = self.r.pubsub() channel.subscribe(self.channel) channel.parse_response() websocket_fd = uwsgi.connection_fd() redis_fd = channel.connection._sock.fileno() while True: uwsgi.wait_fd_read(websocket_fd, 3) uwsgi.wait_fd_read(redis_fd) uwsgi.suspend() fd = uwsgi.ready_fd() if fd > -1: if fd == websocket_fd: uwsgi.websocket_recv_nb() elif fd == redis_fd: wsdata = channel.parse_response()[2] uwsgi.websocket_send(wsdata) else: uwsgi.websocket_recv_nb() time.sleep(1)
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() while True: for method_frame, _, body in channel.consume(queue): try: uwsgi.websocket_send(body) except OSError as error: print(error) sys.exit(1) # Kill process and force uWSGI to Respawn else: # acknowledge the message channel.basic_ack(method_frame.delivery_tag)
def send(self, obj): uwsgi.websocket_send(obj, request_context=self.request_context)
def send(self, msg): uwsgi.websocket_send(msg)
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])
def send(self, message, binary=None): try: uwsgi.websocket_send(message) except IOError as e: self.close() raise WebSocketError(e)
def send(self, msg): """Send message to websocket.""" uwsgi.websocket_send(msg)