Created
February 28, 2020 16:18
-
-
Save rdeioris/9e9343121ab4e2c241083b61eb6d5951 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import socket | |
import time | |
import select | |
class MultiClientServer: | |
def __init__(self, address, port): | |
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
self.socket.bind((address, port)) | |
self.socket.listen(10) | |
self.clients = [] | |
def run(self): | |
while True: | |
self.tick() | |
def tick(self): | |
# reactor pattern | |
interesting_sockets = self.clients + [self.socket] | |
ready_sockets, _, _ = select.select(interesting_sockets, [], []) | |
for ready_socket in ready_sockets: | |
if ready_socket == self.socket: | |
new_client, sender = self.socket.accept() | |
print('new connection from', sender) | |
self.clients.append(new_client) | |
else: | |
data = ready_socket.recv(4096) | |
if not data: | |
self.clients.remove(ready_socket) | |
ready_socket.close() | |
else: | |
print(data) | |
MultiClientServer('127.0.0.1', 9090).run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment