-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
55 lines (44 loc) · 1.56 KB
/
server.py
File metadata and controls
55 lines (44 loc) · 1.56 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
50
51
52
53
54
55
# server_async.py
import asyncio
class ServerConnection:
def __init__(self, msg):
self.msg = msg
self.connections = {} # writer -> addr
async def handle_peer(self, reader, writer):
addr = writer.get_extra_info("peername")
self.connections[writer] = addr
print(f"{addr} connected")
await self.send_peers()
try:
while True:
data = await reader.read(1024)
if not data:
break
text = data.decode("utf-8")
if text.lower().startswith("q"):
break
elif text == "req":
writer.write(self.msg)
await writer.drain()
finally:
await self.disconnect(writer)
async def disconnect(self, writer):
addr = self.connections.pop(writer, None)
if addr:
print(f"{addr} disconnected")
writer.close()
await writer.wait_closed()
await self.send_peers()
async def send_peers(self):
peer_list = ",".join(addr[0] for addr in self.connections.values()) + ","
payload = b"\x11" + peer_list.encode("utf-8")
for writer in list(self.connections.keys()):
writer.write(payload)
await writer.drain()
async def run(self):
server = await asyncio.start_server(
self.handle_peer, "127.0.0.1", 3000
)
print("------------ Server Running ---------------------")
async with server:
await server.serve_forever()