-
Notifications
You must be signed in to change notification settings - Fork 0
/
multicon-server.py
83 lines (50 loc) · 1.51 KB
/
multicon-server.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import socket
import selectors
import types
import sys
sel = selectors.DefaultSelector()
def accept_wrapper(sock):
conn, addr = sock.accept()
print("accepted connection from: ", addr)
conn.setblocking(False)
data = types.SimpleNamespace(addr=addr, inb=b'', outb = b'')
events = selectors.EVENT_READ | selectors.EVENT_WRITE
sel.register(conn, events, data=data)
def service_connection(key, mask):
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024)
if recv_data:
data.outb += recv_data
else:
print("closing connection to: ", data.addr)
sel.unregister(sock)
sock.close()
if mask & selectors.EVENT_WRITE:
if data.outb:
print("echoing: ", repr(data.outb), "to connection: ", data.addr)
sent = sock.send(data.outb)
data.outb = data.outb[sent:]
if len(sys.argv) != 3:
print("usage: ", sys.argv[0], "<host> <port>")
sys.exit(1)
host, port = sys.argv[1], int(sys.argv[2])
lisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lisock.bind((host, port))
lisock.listen()
print("listening on: ", (host, port))
lisock.setblocking(False)
sel.register(lisock, selectors.EVENT_READ, data=None)
try:
while True:
event = sel.select(timeout=None)
for key, mask in event:
if key.data is None:
accept_wrapper(key.fileobj)
else:
service_connection(key, mask)
except KeyboardInterrupt:
print("caught keyboard interrupt")
finally:
sel.close()