-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmulticonn_client.py
More file actions
45 lines (42 loc) · 1.59 KB
/
multiconn_client.py
File metadata and controls
45 lines (42 loc) · 1.59 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
import sys
import socket
import selectors
import types
sel = selectors.DefaultSelector()
messages = [b"Message from client 1", b"Message from client 2"]
def start_connection(host, port, num_conns):
server_addr = (host, port)
for i in range(0, num_conns):
connid = i + 1
print(f"Starting connection to {connid}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)
sock.connect_ex(server_addr)
events = selectors.EVENT_READ |selectors.EVENT_WRITE
data = types.SimpleNamespace(
connid = connid,
msg_total = sum(len(m) for m in messages),
recv_total = 0,
messages = messages.copy(),
outb = b"",
)
sel.register(sock, events, data=data)
def service_connection(key, mask):
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024) # Should be ready to read
if recv_data:
print(f"Recived {recv_data!r} from connection {data.connid}")
data.recv_total += len(recv_data)
if not recv_data or data.recv_total == data.msg_total:
print(f"Closing connection {data.connid}")
sel.unregister(sock)
sock.close()
if mask & selectors.EVENT_WRITE:
if not data.outb and data.messages:
data.outb = data.messages.pop(0)
if data.outb:
print(f"Sending {data.outb!r} to connection {data.connid}")
sent = sock.send(data.outb) # Should be ready to write
data.outb = data.outb[sent:]