Created
October 16, 2022 13:40
-
-
Save yaniv-aknin/fa80327c709f3a35fdadb8d92814ee2b to your computer and use it in GitHub Desktop.
Simple multi-client server for my nephew
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import select | |
import socket | |
def parse_options(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-p', '--port', type=int, required=True) | |
options = parser.parse_args() | |
return options | |
def main(options): | |
clients = [] | |
server = socket.socket() | |
server.bind(('0.0.0.0', options.port)) | |
server.listen(1) | |
print(f'listening on port {options.port}') | |
while True: | |
rlist, wlist, xlist = select.select([server] + clients, [], []) | |
for sock in rlist: | |
if sock is server: | |
client, addr = server.accept() | |
print(f'new client from {addr}') | |
clients.append(client) | |
continue | |
msg = sock.recv(1024) | |
for client in clients: | |
if sock is client: | |
continue | |
client.send(msg) | |
if __name__ == '__main__': | |
main(parse_options()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment