本文整理汇总了Python中aiohttp.web.WebSocketResponse方法的典型用法代码示例。如果您正苦于以下问题:Python web.WebSocketResponse方法的具体用法?Python web.WebSocketResponse怎么用?Python web.WebSocketResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp.web
的用法示例。
在下文中一共展示了web.WebSocketResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wshandler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def wshandler(request):
app = request.app
ws = web.WebSocketResponse()
await ws.prepare(request)
app["sockets"].append(ws)
if app["game_is_running"] == False:
asyncio.ensure_future(game_loop(app))
while 1:
msg = await ws.receive()
if msg.tp == web.MsgType.text:
print("Got message %s" % msg.data)
ws.send_str("Pressed key code: {}".format(msg.data))
elif msg.tp == web.MsgType.close or\
msg.tp == web.MsgType.error:
break
app["sockets"].remove(ws)
print("Closed connection")
return ws
示例2: ws_handler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def ws_handler(self, request):
ws = web.WebSocketResponse()
await ws.prepare(request)
if self.ws is not None:
await self.ws.close()
self.ws = ws
_, unfinished = await asyncio.wait(
[
self._websocket_receive(ws),
self._websocket_send(ws)
],
return_when=asyncio.FIRST_COMPLETED
)
for task in unfinished:
task.cancel()
return ws
示例3: handler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def handler(self, request):
headers = request.headers
if (
headers.get("connection", "").lower() == "upgrade"
and headers.get("upgrade", "").lower() == "websocket"
and request.method == "GET"
):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await ws.send_str(msg.data)
elif msg.type == aiohttp.WSMsgType.BINARY:
await ws.send_bytes(msg.data)
elif msg.type == aiohttp.WSMsgType.PING:
await ws.ping()
elif msg.type == aiohttp.WSMsgType.PONG:
await ws.pong()
elif ws.closed:
await ws.close(code=ws.close_code, message=msg.extra)
return ws
else:
return web.Response(text=request.path)
示例4: wshandler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def wshandler(request):
app = request.app
ws = web.WebSocketResponse()
await ws.prepare(request)
app["sockets"].append(ws)
while 1:
msg = await ws.receive()
if msg.tp == web.MsgType.text:
print("Got message %s" % msg.data)
ws.send_str("Pressed key code: {}".format(msg.data))
elif msg.tp == web.MsgType.close or\
msg.tp == web.MsgType.error:
break
app["sockets"].remove(ws)
print("Closed connection")
return ws
示例5: create_account_link_server
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def create_account_link_server(aiohttp_client, handle_server_msgs):
"""Create a websocket server."""
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
try:
await handle_server_msgs(ws)
finally:
await ws.close()
return ws
app = web.Application()
app.add_routes([web.get("/ws", websocket_handler)])
client = await aiohttp_client(app)
return await client.ws_connect("/ws")
示例6: connection_handler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def connection_handler(self, request):
ws = web.WebSocketResponse()
await ws.prepare(request)
send_msg = self.get_send_msg(self._data)
await ws.send_str(send_msg)
conn_chan = TqChan(self._api, last_only=True)
self._conn_diff_chans.add(conn_chan)
try:
async for msg in ws:
pack = simplejson.loads(msg.data)
if pack["aid"] == 'peek_message':
last_diff = await conn_chan.recv()
send_msg = self.get_send_msg(last_diff)
await ws.send_str(send_msg)
except Exception as e:
await conn_chan.close()
self._conn_diff_chans.remove(conn_chan)
示例7: wshandler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def wshandler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type == web.MsgType.text:
await ws.send_str("Hello, {}".format(msg.data))
elif msg.type == web.MsgType.binary:
await ws.send_bytes(msg.data)
elif msg.type == web.MsgType.close:
break
return ws
示例8: websocket_connection
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def websocket_connection(self, websocket: web.WebSocketResponse) -> Tuple[Callable, Callable]:
# Called when a websocket client is connected
self.log('websocket client connected')
async def _receive(data: Union[str, bytes]) -> None:
# Called when the websocket receives data
self.log('websocket data received: {}'.format(data))
await websocket.send_str('response')
async def _close() -> None:
# Called when the websocket is closed by the other end
self.log('websocket closed')
# Receiving function and closure function returned as tuple
return _receive, _close
示例9: websocket_connection
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def websocket_connection(self, websocket: web.WebSocketResponse) -> Tuple[Callable, Callable]:
# Called when a websocket client is connected
self.log('websocket client connected')
async def _receive(data: Union[str, bytes]) -> None:
# Called when the websocket receives data
self.log('websocket data received: {}'.format(data))
await websocket.send_str('response {}'.format(str(uuid.uuid4())))
async def _close() -> None:
# Called when the websocket is closed by the other end
self.log('websocket closed')
# Receiving function and closure function returned as tuple
return _receive, _close
示例10: websocket_simple
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def websocket_simple(self, websocket: web.WebSocketResponse) -> None:
self.websocket_connected = True
示例11: websocket_with_header
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def websocket_with_header(self, websocket: web.WebSocketResponse, request: web.Request) -> None:
self.websocket_header = request.headers.get('User-Agent')
示例12: websocket_data
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def websocket_data(self, websocket: web.WebSocketResponse) -> Callable:
async def _receive(data: Union[str, bytes]) -> None:
self.websocket_received_data = data
return _receive
示例13: log_websocket
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def log_websocket(request: web.Request) -> web.WebSocketResponse:
ws = web.WebSocketResponse()
await ws.prepare(request)
sockets.append(ws)
log.debug(f"Connection from {request.remote} opened")
authenticated = False
async def close_if_not_authenticated():
await asyncio.sleep(5, loop=get_loop())
if not authenticated:
await ws.close(code=4000)
log.debug(f"Connection from {request.remote} terminated due to no authentication")
asyncio.ensure_future(close_if_not_authenticated())
try:
async for msg in ws:
if msg.type != web.WSMsgType.TEXT:
continue
if is_valid_token(msg.data):
await ws.send_json({"auth_success": True})
await ws.send_json({"history": list(handler.lines)})
if not authenticated:
log.debug(f"Connection from {request.remote} authenticated")
handler.listeners.append(ws)
authenticated = True
elif not authenticated:
await ws.send_json({"auth_success": False})
except Exception:
try:
await ws.close()
except Exception:
pass
if authenticated:
handler.listeners.remove(ws)
log.debug(f"Connection from {request.remote} closed")
sockets.remove(ws)
return ws
示例14: __init__
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def __init__(self, up_conn: aiohttp.ClientWebSocketResponse,
down_conn: web.WebSocketResponse, *,
downstream_callback: Awaitable = None,
upstream_callback: Awaitable = None,
ping_callback: Awaitable = None):
self.up_conn = up_conn
self.down_conn = down_conn
self.upstream_buffer = asyncio.Queue()
self.upstream_buffer_task = None
self.downstream_cb = downstream_callback
self.upstream_cb = upstream_callback
self.ping_cb = ping_callback
示例15: websocket_handler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import WebSocketResponse [as 别名]
def websocket_handler(self, request):
ws = web.WebSocketResponse()
await ws.prepare(request)
request.app["websockets"].append(ws)
try:
async for msg in ws:
await ws.send_json({"type": "message", "message_sent": msg.json()})
finally:
request.app["websockets"].remove(ws)
return ws