def wshandler(request): resp = WebSocketResponse() ok, protocol = resp.can_start(request) if not ok: with open(WS_FILE, 'rb') as fp: return Response(body=fp.read(), content_type='text/html') resp.start(request) print('Someone joined.') for ws in request.app['sockets']: ws.send_str('Someone joined') request.app['sockets'].append(resp) try: while True: msg = yield from resp.receive_str() print(msg) for ws in request.app['sockets']: if ws is not resp: ws.send_str(msg) except WSClientDisconnectedError: if resp not in request.app['sockets']: return resp request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: ws.send_str('Someone disconnected.') raise
def wshandler(request): print("wshandler", request) resp = WebSocketResponse() ok, protocol = resp.can_start(request) if not ok: print("http") with open(WS_FILE, 'rb') as fp: return Response(body=fp.read(), content_type='text/html') print("ws") resp.start(request) print('Someone joined.') for ws in request.app['sockets']: ws.send_str('Someone joined') request.app['sockets'].append(resp) while True: msg = yield from resp.receive() if msg.tp == MsgType.text: for ws in request.app['sockets']: if ws is not resp: ws.send_str(msg.data) else: break request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: ws.send_str('Someone disconnected.') return resp
def test_pong_closing(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) ws.close() with self.assertRaises(RuntimeError): ws.pong()
def test_pong_closed(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) self.loop.run_until_complete(ws.close()) with self.assertRaises(RuntimeError): ws.pong()
def wso(request): global wsk global wst wsk0 = WebSocketResponse() wsk0.start(request) unauth = True while True: msg = yield from wsk0.receive() if msg.tp == MsgType.text: print("Screen") print(msg.data) if unauth: wsk0.auth = msg.data wsk[wsk0.auth] = wsk0 unauth = False continue if msg.data == 'close': yield from wsk0.close() wsk.pop(wsk0.auth, None) break else: wst[wsk0.auth].send_str(msg.data) elif msg.tp == MsgType.close: break elif msg.tp == MsgType.error: break wsk.pop(wsk0.auth, None) return wsk0
def test_concurrent_receive(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) ws._waiting = True self.assertRaises( RuntimeError, self.loop.run_until_complete, ws.receive())
def test_close_idempotent(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) writer = mock.Mock() ws._writer = writer self.assertTrue( self.loop.run_until_complete(ws.close(code=1, message='message1'))) self.assertTrue(ws.closed) self.assertFalse( self.loop.run_until_complete(ws.close(code=2, message='message2')))
def test_receive_timeouterror(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) res = asyncio.Future(loop=self.loop) res.set_exception(asyncio.TimeoutError()) ws._reader.read.return_value = res self.assertRaises(asyncio.TimeoutError, self.loop.run_until_complete, ws.receive())
def test_multiple_receive_on_close_connection(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) self.loop.run_until_complete(ws.close()) self.loop.run_until_complete(ws.receive()) self.loop.run_until_complete(ws.receive()) self.loop.run_until_complete(ws.receive()) self.loop.run_until_complete(ws.receive()) self.assertRaises( RuntimeError, self.loop.run_until_complete, ws.receive())
def test_receive_timeouterror(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) res = asyncio.Future(loop=self.loop) res.set_exception(asyncio.TimeoutError()) ws._reader.read.return_value = res self.assertRaises( asyncio.TimeoutError, self.loop.run_until_complete, ws.receive())
def test_write_eof_exception(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) ws._closing_fut.set_exception(ValueError()) @asyncio.coroutine def go(): with self.assertRaises(ValueError): yield from ws.write_eof() self.loop.run_until_complete(go())
def test_double_close(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) writer = mock.Mock() ws._writer = writer ws.close(code=1, message='message1') self.assertTrue(ws.closing) with self.assertRaisesRegex(RuntimeError, 'Already closing'): ws.close(code=2, message='message2') self.assertTrue(ws.closing) writer.close.assert_called_once_with(1, 'message1')
def go(): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) @asyncio.coroutine def receive(): return websocket.Message(websocket.MSG_BINARY, b'data', b'') ws.receive = receive with self.assertRaises(TypeError): yield from ws.receive_str()
def test_write_eof_idempotent(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) self.loop.run_until_complete(ws.close()) @asyncio.coroutine def go(): yield from ws.write_eof() yield from ws.write_eof() yield from ws.write_eof() self.loop.run_until_complete(go())
def create_wsgi_environ(self, message, payload): environ = super().create_wsgi_environ(message, payload) environ['wsgi.websocket'] = None self.method = message.method self.headers = message.headers self._writer = self.writer self._reader = self.reader self.version = message.version self.path = environ.get('PATH_INFO', '') ws = WebSocketResponse() ok, protocol = ws.can_start(self) if ok: ws.start(self) environ['wsgi.websocket'] = ws return environ
def wsi(request): global wst wst = WebSocketResponse() wst.start(request) while True: msg = yield from wst.receive() if msg.tp == MsgType.text: if msg.data == 'close': yield from wst.close() break elif msg.tp == MsgType.close: break elif msg.tp == MsgType.error: break return wst
def test_start_twice_idempotent(self): req = self.make_request('GET', '/') ws = WebSocketResponse() with self.assertWarns(DeprecationWarning): impl1 = ws.start(req) impl2 = ws.start(req) self.assertIs(impl1, impl2)
def test_start_twice_idempotent(make_request): req = make_request('GET', '/') ws = WebSocketResponse() with pytest.warns(DeprecationWarning): impl1 = ws.start(req) impl2 = ws.start(req) assert impl1 is impl2
def test_start_twice_idempotent(self): req = self.make_request("GET", "/") ws = WebSocketResponse() with self.assertWarns(DeprecationWarning): impl1 = ws.start(req) impl2 = ws.start(req) self.assertIs(impl1, impl2)
def test_close_exc2(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) exc = ValueError() self.writer.close.side_effect = exc ws._writer = self.writer self.loop.run_until_complete(ws.close()) self.assertTrue(ws.closed) self.assertIs(ws.exception(), exc) ws._closed = False self.writer.close.side_effect = asyncio.CancelledError() self.assertRaises(asyncio.CancelledError, self.loop.run_until_complete, ws.close())
def test_receive_msg_exc_in_reader(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) exc = ValueError() res = asyncio.Future(loop=self.loop) res.set_exception(exc) ws._reader.read.return_value = res @asyncio.coroutine def go(): with self.assertRaises(ValueError): yield from ws.receive_msg() self.assertIs(ws._closing_fut.exception(), exc) self.loop.run_until_complete(go())
def test_receive_exc_in_reader(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) exc = ValueError() res = asyncio.Future(loop=self.loop) res.set_exception(exc) ws._reader.read.return_value = res @asyncio.coroutine def go(): msg = yield from ws.receive() self.assertTrue(msg.tp, MsgType.error) self.assertIs(msg.data, exc) self.assertIs(ws.exception(), exc) self.loop.run_until_complete(go())
def test_receive_client_disconnected(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) exc = errors.ClientDisconnectedError() res = asyncio.Future(loop=self.loop) res.set_exception(exc) ws._reader.read.return_value = res @asyncio.coroutine def go(): msg = yield from ws.receive() self.assertTrue(ws.closed) self.assertTrue(msg.tp, MsgType.close) self.assertIs(msg.data, None) self.assertIs(ws.exception(), None) self.loop.run_until_complete(go())
def wshandler(request): resp = WebSocketResponse() ok, protocol = resp.can_start(request) if not ok: with open(WS_FILE, 'rb') as fp: return Response(body=fp.read(), content_type='text/html') sockets = request.app['sockets'] if len(sockets) == 0: restart_game() sockets.append(resp) resp.start(request) # login msg = yield from resp.receive() keycode = msg.data existing = USERMAP.get(keycode) if not existing or not existing.closed: random.seed(random.SystemRandom()) keycode = ''.join(random.sample(string.ascii_letters, 32)) USERMAP[keycode] = resp # communicate update_id_info(sockets) resp.send_str(json.dumps(ACTIONS)) while True: msg = yield from resp.receive() if msg.tp == MsgType.text: move = json.loads(msg.data)+[len(ACTIONS)] ACTIONS.append(move) for ws in sockets: ws.send_str(json.dumps([move])) else: break sockets.remove(resp) update_id_info(sockets) return resp
def test_close_exc(self): req = self.make_request('GET', '/') reader = self.reader.set_parser.return_value = mock.Mock() ws = WebSocketResponse() ws.start(req) exc = ValueError() reader.read.return_value = asyncio.Future(loop=self.loop) reader.read.return_value.set_exception(exc) self.loop.run_until_complete(ws.close()) self.assertTrue(ws.closed) self.assertIs(ws.exception(), exc) ws._closed = False reader.read.return_value = asyncio.Future(loop=self.loop) reader.read.return_value.set_exception(asyncio.CancelledError()) self.assertRaises(asyncio.CancelledError, self.loop.run_until_complete, ws.close()) self.assertEqual(ws.close_code, 1006)
def handle(self, request): self.request = request ws = WebSocketResponse() ws.start(request) connection = yield from asyncio_redis.Connection.create(host='127.0.0.1', port=6379) subscriber = yield from connection.start_subscribe() yield from subscriber.subscribe(['ch1', 'ch2']) print('Connection opened') try: # Kick off both coroutines in parallel, and then block # until both are completed. yield from asyncio.gather(self.handle_ws(ws), self.handle_redis(subscriber)) #yield from self.handle_ws(ws) except Exception as e: # Don't do except: pass import traceback traceback.print_exc() finally: print('Connection closed') return ws
def test_start_without_upgrade(self): req = self.make_request('GET', '/', headers=CIMultiDict({})) ws = WebSocketResponse() with self.assertRaises(HTTPBadRequest): ws.start(req)
def test_start_invalid_method(self): req = self.make_request('POST', '/') ws = WebSocketResponse() with self.assertRaises(HTTPMethodNotAllowed): ws.start(req)
def test_send_bytes_nonbytes(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) with self.assertRaises(TypeError): ws.send_bytes('string')
def test_can_start_started(self): req = self.make_request('GET', '/') ws = WebSocketResponse() ws.start(req) with self.assertRaisesRegex(RuntimeError, 'Already started'): ws.can_start(req)