-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_socket_server_6_asyncio.py
More file actions
executable file
·49 lines (41 loc) · 1.21 KB
/
tcp_socket_server_6_asyncio.py
File metadata and controls
executable file
·49 lines (41 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python3
"""
Final version of asyncio socket server.
Using standard high-level API with streams.
"""
import asyncio
HOST, PORT = ('localhost', 12345)
async def handle_connection(reader, writer):
addr = writer.get_extra_info("peername")
print("Connected by", addr)
while True:
# Receive
try:
data = await reader.read(1024) # New
except ConnectionError:
print(f"Client suddenly closed while receiving from {addr}")
break
print(f"Received {data} from: {addr}")
if not data:
break
# Process
if data == b"close":
break
data = data.upper()
# Send
print(f"Sending: {data} to: {addr}")
try:
writer.write(data) # New
await writer.drain()
except ConnectionError:
print(f"Client suddenly closed, cannot send")
break
# Disconnect
writer.close()
print("Disconnected by", addr)
async def main(host, port):
server = await asyncio.start_server(handle_connection, host, port)
print(f"Start server...")
async with server:
await server.serve_forever()
asyncio.run( main(HOST, PORT) )