Skip to content

Instantly share code, notes, and snippets.

@sooop

sooop/multiserver.py Secret

Last active Nov 19, 2019
Embed
What would you like to do?
from multiprocessing import Process
import selectors
import socket
import time
import random
def read_handler(
sock: socket.socket,
sel_: selectors.BaseSelector):
data = sock.recv(1000)
if data:
print(f'echoing: {repr(data)} | '
f'{sock.getpeername()}')
time.sleep(random.randrange(1, 10) / 10)
sock.send(data)
else:
print('closing...')
sel_.unregister(sock)
sock.close()
def accept_handler(
sock: socket.socket,
sel_: selectors.BaseSelector):
conn: socket.socket
addr: str
conn, addr = sock.accept()
print(f'accepted: {conn.getpeername()} from {addr}')
conn.setblocking(False)
sel_.register(conn, selectors.EVENT_READ, read_handler)
def start_server(port=5577):
sel = selectors.DefaultSelector()
sock = socket.socket()
sock.bind(('localhost', port))
sock.setblocking(False)
sock.listen(100)
sel.register(sock, selectors.EVENT_READ, accept_handler)
while True:
events = sel.select()
for key, mask in events:
callback = key.data
callback(key.fileobj, sel)
def start_client(word: str, port=5577):
sock = socket.socket()
sock.connect(('localhost', port))
sock.sendall(word.encode())
time.sleep(random.randrange(1, 5) / 10)
data = sock.recv(1024)
print(data.decode())
sock.close()
def main():
srv = Process(target=start_server)
srv.start()
words = 'apple hello mango world banana organe'.split()
for i in range(10):
Process(target=start_client,
args=(f'[{i+1}] ' + random.choice(words),))\
.start()
srv.join(9)
srv.kill()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment