asyncio.run(main_async())
async def main_async():
address = ('127.0.0.1', 4321)
server = run_async_server(address) # 코루틴 인스턴스
asyncio.create_task(server)
results = await run_async_client(address)
for number, outcome in results:
print(f'클라이언트: {number}는 {outcome}')
async def run_async_server(address):
server = await asyncio.start_server(
handle_async_connection, *address)
async with server:
await server.serve_forever()
async def handle_async_connection(reader, writer):
session = AsyncSession(reader, writer)
try:
await session.loop()
except EOFError:
pass
with open('data.txt') as f:
for line in f:
print(line)
with 문 왜 써?
파이썬의 컨텍스트 매니저
async with 클래스() as 변수:
코드
class 클래스이름:
async def __aenter__(self):
"""
이 함수에서 값을 반환하면, as에 지정한 변수에 들어갑니다.
"""
코드
async def __aexit__(self, exc_type, exc_value, traceback):
"""
async with as를 완전히 벗어나면 호출됩니다.
"""
코드
asyncio.run(main_async())
async def main_async():
address = ('127.0.0.1', 4321)
server = run_async_server(address) # 코루틴 인스턴스
asyncio.create_task(server)
results = await run_async_client(address)
for number, outcome in results:
print(f'클라이언트: {number}는 {outcome}')
async def run_async_client(address):
# 서버가 시작될 수 있게 기다려주기
await asyncio.sleep(0.1)
streams = await asyncio.open_connection(*address) # New
client = AsyncClient(*streams) # New
async with client.session(1, 5, 3):
results = [(x, await client.report_outcome(x))
async for x in client.request_numbers(5)]
async with client.session(10, 15, 12):
async for number in client.request_numbers(5):
outcome = await client.report_outcome(number)
results.append((number, outcome))
_, writer = streams # 새 기능
writer.close() # 새 기능
await writer.wait_closed() # 새 기능
return results
class AsyncClient(AsyncConnectionBase):
def __init__(self, *args):
super().__init__(*args)
self._clear_state()
def _clear_state(self):
self.secret = None
self.last_distance = None
@contextlib.asynccontextmanager # 변경됨
async def session(self, lower, upper, secret): # 변경됨
print(f'\n{lower}와 {upper} 사이의 숫자를 맞춰보세요!'
f' 쉿! 그 숫자는 {secret} 입니다.')
self.secret = secret
await self.send(f'PARAMS {lower} {upper}') # 변경됨
try:
yield
finally:
self._clear_state()
await self.send('PARAMS 0 -1') # 변경됨
async def request_numbers(self, count): # 변경됨
for _ in range(count):
await self.send('NUMBER') # 변경됨
data = await self.receive() # 변경됨
yield int(data)
if self.last_distance == 0:
return