Skip to content

Commit

Permalink
fix #73: not block in the receiving loop (#74)
Browse files Browse the repository at this point in the history
* fix #73: not block in the receiving loop

* rewrite

* grumble

* bugfix

* %s
  • Loading branch information
twd2 authored and iceboy233 committed Aug 22, 2019
1 parent 3124dd9 commit f6b84b6
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions jd4/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
from aiohttp import ClientSession, CookieJar
from asyncio import get_event_loop
from asyncio import CancelledError, Queue, get_event_loop
from appdirs import user_config_dir
from os import path
from urllib.parse import urljoin
Expand Down Expand Up @@ -57,10 +57,29 @@ async def post_json(self, relative_url, **kwargs):
async def judge_consume(self, handler_type):
async with self.ws_connect(self.full_url('judge/consume-conn/websocket')) as ws:
logger.info('Connected')
async for msg in ws:
request = json.loads(msg.data)
await handler_type(self, request, ws).handle()
logger.warning('Connection lost with code %d', ws.close_code)
queue = Queue()
async def worker():
try:
while True:
request = await queue.get()
await handler_type(self, request, ws).handle()
except CancelledError:
raise
except Exception as e:
logger.exception(e)
await ws.close()
worker_task = get_event_loop().create_task(worker())
try:
while True:
queue.put_nowait(await ws.receive_json())
except TypeError:
pass
logger.warning('Connection lost with code %s', ws.close_code)
worker_task.cancel()
try:
await worker_task
except CancelledError:
pass

async def judge_noop(self):
await self.get_json('judge/noop')
Expand Down

0 comments on commit f6b84b6

Please sign in to comment.