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 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 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 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 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 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 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 __call__(self, environ, start_response): self.environ = environ uwsgi.websocket_handshake() self._req_ctx = None if hasattr(uwsgi, 'request_context'): # uWSGI >= 2.1.x with support for api access across-greenlets self._req_ctx = uwsgi.request_context() else: # use event and queue for sending messages from gevent.event import Event from gevent.queue import Queue from gevent.select import select self._event = Event() self._send_queue = Queue() # spawn a select greenlet def select_greenlet_runner(fd, event): """Sets event when data becomes available to read on fd.""" while True: event.set() select([fd], [], [])[0] self._select_greenlet = gevent.spawn( select_greenlet_runner, uwsgi.connection_fd(), self._event) return self.app(self)
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 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 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 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 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))
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, 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 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 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 start(self): uwsgi.websocket_handshake() self.ctx = uwsgi.request_context() ClientManager.add(self) self.jobs.extend([ gevent.spawn(self._recv_job), gevent.spawn(self._send_job), ]) for j in self.jobs: j.link(self._exit) gevent.joinall(self.jobs)
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 __call__(self, environ, start_response): self.environ = environ if uwsgi and 'uwsgi.version' in environ: # we are running under uwsgi uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', '')) self._sock = None elif 'wsgi.websocket' in environ: self._sock = environ['wsgi.websocket'] #self.version = self._sock.version #self.path = self._sock.path #self.origin = self._sock.origin #self.protocol = self._sock.protocol else: raise RuntimeError('You need to use the gevent-websocket server. ' 'See the Deployment section of the ' 'documentation for more information.') return self.app(self)
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 _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(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 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 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 route_fun(*args, **kwargs): ws = cls() loop = FawnLoop(ws, channel, self) if not request.headers.get("Sec-Websocket-Key"): log.error("Not a websocket request") abort(500) if uwsgi is None: log.erorr("The server is not run with uwsgi. " "Websocket will not work.") abort(426) uwsgi.websocket_handshake(request.headers["Sec-Websocket-Key"], request.headers.get("Origin", "")) ws.request_context = _request_ctx_stack.top ws.app_context = _app_ctx_stack.top ws.open(*args, **kwargs) loop.loop() # Putting app context into implicit again to force app context pop ws.request_context._implicit_app_ctx_stack.append(ws.app_context) # Don't respond here (already done during handshake) return VoidResponse("")
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): 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))
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'] == '/favicon.ico': return "" elif env['PATH_INFO'] == '/foobar/': uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) print "websockets..." r = redis.StrictRedis(host='localhost', port=6379, db=0) channel = r.pubsub() channel.subscribe('foobar') websocket_fd = uwsgi.connection_fd() redis_fd = channel.connection._sock.fileno() while True: # wait max 4 seconds to allow ping to be sent ready = gevent.select.select([websocket_fd, redis_fd], [], [], 4.0) # send ping on timeout if not ready[0]: uwsgi.websocket_recv_nb() for fd in ready[0]: if fd == websocket_fd: msg = uwsgi.websocket_recv_nb() if msg: r.publish('foobar', msg) elif fd == redis_fd: msg = channel.parse_response() # only interested in user messages if msg[0] == 'message': uwsgi.websocket_send("[%s] %s" % (time.time(), msg))
def websocket_handshake(self, key, origin): ''' ''' return uwsgi.websocket_handshake(key, origin)
uwsgi.websocket_recv_nb() """ def uwsgi_pypy_websocket_recv_nb(): wsgi_req = uwsgi_pypy_current_wsgi_req() ub = lib.uwsgi_websocket_recv_nb(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_nb = uwsgi_pypy_websocket_recv_nb """ uwsgi.websocket_handshake(key, origin) """ def uwsgi_pypy_websocket_handshake(key, origin=''): wsgi_req = uwsgi_pypy_current_wsgi_req() if lib.uwsgi_websocket_handshake(wsgi_req, ffi.new('char[]', key), len(key), ffi.new('char[]', origin), len(origin)) < 0: raise IOError("unable to complete websocket handshake") uwsgi.websocket_handshake = uwsgi_pypy_websocket_handshake """ uwsgi.websocket_send(msg)
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'])).encode() elif env['PATH_INFO'] == '/favicon.ico': return b"" elif env['PATH_INFO'] == '/foobar/': uwsgi.websocket_handshake() print("websockets...") # a future for waiting for redis connection f = GreenFuture() asyncio.Task(redis_subscribe(f)) # the result() method will switch greenlets if needed subscriber = f.result() # open another redis connection for publishing messages f0 = GreenFuture() t = asyncio.Task(redis_open(f0)) connection = f0.result() myself = greenlet.getcurrent() myself.has_ws_msg = False # start monitoring websocket events asyncio.get_event_loop().add_reader(uwsgi.connection_fd(), ws_recv_msg, myself) # add a 4 seconds timer to manage ping/pong asyncio.get_event_loop().call_later(4, ws_recv_msg, myself) # add a coroutine for redis messages f = GreenFuture() asyncio.Task(redis_wait(subscriber, f)) # switch again f.greenlet.parent.switch() while True: # any redis message in the queue ? if f.done(): msg = f.result() uwsgi.websocket_send("[%s] %s" % (time.time(), msg)) # restart coroutine f = GreenFuture() asyncio.Task(redis_wait(subscriber, f)) if myself.has_ws_msg: myself.has_ws_msg = False msg = uwsgi.websocket_recv_nb() if msg: asyncio.Task(redis_publish(connection, msg)) # switch again f.greenlet.parent.switch()
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])
def application(env, start_response): request = Request(env) try: uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) except OSError as err: logging.info('handshake_failed') else: with cursor_for_request(request) as cursor: db_connection = cursor.connection db_connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) db_conn_fd = db_connection.fileno() websocket_fd = uwsgi.connection_fd() logging.info('connection established') try: while True: uwsgi.wait_fd_read(websocket_fd) uwsgi.wait_fd_read(db_conn_fd) uwsgi.suspend() fd = uwsgi.ready_fd() if fd == websocket_fd: cmd_json = uwsgi.websocket_recv_nb() if cmd_json: cmd = json.loads(cmd_json.decode('utf-8')) if cmd: try: if cmd['method'] != 'ping': logging.info('command received: %s' % cmd['method']) if cmd['method'] == 'request': request_method(cmd, cursor) elif cmd['method'] == 'attach': attach_method(cmd, cursor, db_connection) elif cmd['method'] == 'detach': detach_method(cmd, cursor, db_connection, env) except Warning as err: logging.error(str(err)) # uwsgi.websocket_send(json.dumps({ # "method": "log", # "args": { # "level": "warning", # "message": err.diag.message_primary # } # })) elif fd == db_conn_fd: handle_db_notifications(db_connection) else: logging.info( 'timeout reached') # This is never reached # handle timeout of above wait_fd_read for ping/pong uwsgi.websocket_recv_nb() except (OSError, IOError) as err: logging.info('connection closed (role: %s)' % env['DB_USER']) return []