Last active
April 6, 2021 16:34
-
-
Save abul4fia/37c51311e8feced1b881340485a12f36 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 threading | |
import queue | |
import time | |
import sys | |
class TCPServer: | |
def __init__(self, port, q): | |
self.clientes = [] | |
self.port = port | |
self.q = q | |
self.hilo_socket = None | |
self.hilo_cola = None | |
self.lock = threading.Lock() | |
def start(self): | |
self.s = socket.socket() | |
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
self.s.bind(("", self.port)) | |
self.s.listen() | |
self.hilo_espera = threading.Thread(target=self.espera_clientes) | |
self.hilo_espera.start() | |
self.hilo_cola = threading.Thread(target=self.espera_cola) | |
self.hilo_cola.start() | |
def espera_clientes(self): | |
while True: | |
cliente, addr = self.s.accept() | |
print("Nuevo cliente desde", addr) | |
self.lock.acquire() | |
self.clientes.append(cliente) | |
self.lock.release() | |
print("Clientes conectados:", len(self.clientes)) | |
def espera_cola(self): | |
while True: | |
dato = self.q.get() | |
print("Recibido dato", dato) | |
self.lock.acquire() | |
clientes_potenciales = self.clientes.copy() | |
self.lock.release() | |
clientes_ausentes = [] | |
for c in clientes_potenciales: | |
try: | |
c.send(str(dato).encode("utf8") + b"\r\n") | |
except Exception as e: | |
print("Problema con {}: {}".format(c,e)) | |
print("Eliminando cliente") | |
c.close() | |
clientes_ausentes.append(c) | |
self.lock.acquire() | |
self.clientes = [c for c in self.clientes if c not in clientes_ausentes ] | |
self.lock.release() | |
print("Clientes conectados:", len(self.clientes)) | |
def main(): | |
if len(sys.argv) > 1: | |
port = int(sys.argv[1]) | |
else: | |
port = 8888 | |
q = queue.Queue() | |
server = TCPServer(port, q) | |
server.start() | |
n = 0 | |
while True: | |
n += 1 | |
if n%5 == 0: | |
print("Pintando", n) | |
q.put(n) | |
time.sleep(1) | |
print('-Waiting Mask-') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment