You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.8 KiB
62 lines
1.8 KiB
9 months ago
|
import socket
|
||
|
import threading
|
||
|
|
||
|
# Configuración del servidor
|
||
|
HOST = ''
|
||
|
PORT = 5555
|
||
|
|
||
|
# Crear un socket del servidor
|
||
|
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
|
server_socket.bind((HOST, PORT))
|
||
|
server_socket.listen()
|
||
|
|
||
|
# Lista para almacenar conexiones de clientes
|
||
|
clients = []
|
||
|
|
||
|
def broadcast(message, client_socket):
|
||
|
"""Envía el mensaje a todos los clientes conectados."""
|
||
|
for client in clients:
|
||
|
# Excepto al cliente que envió el mensaje
|
||
|
if client != client_socket:
|
||
|
try:
|
||
|
client.send(message)
|
||
|
except:
|
||
|
# Eliminar clientes que no responden
|
||
|
clients.remove(client)
|
||
|
|
||
|
def handle_client(client_socket):
|
||
|
"""Maneja la conexión de un cliente."""
|
||
|
while True:
|
||
|
try:
|
||
|
# Recibir mensajes del cliente
|
||
|
message = client_socket.recv(1024)
|
||
|
if not message:
|
||
|
break
|
||
|
|
||
|
# Imprimir el mensaje en el servidor
|
||
|
print(f"Mensaje de {client_socket.getpeername()}: {message.decode('utf-8')}")
|
||
|
# Broadcast del mensaje a todos los clientes
|
||
|
broadcast(message, client_socket)
|
||
|
|
||
|
except:
|
||
|
# Eliminar clientes que causan problemas
|
||
|
clients.remove(client_socket)
|
||
|
break
|
||
|
|
||
|
def main():
|
||
|
print(f"Servidor en escucha en {HOST}:{PORT}")
|
||
|
|
||
|
while True:
|
||
|
# Aceptar nuevas conexiones
|
||
|
client_socket, address = server_socket.accept()
|
||
|
print(f"Conexión aceptada desde {address}")
|
||
|
|
||
|
# Agregar el nuevo cliente a la lista
|
||
|
clients.append(client_socket)
|
||
|
|
||
|
# Iniciar un hilo para manejar al cliente
|
||
|
thread = threading.Thread(target=handle_client, args=(client_socket,))
|
||
|
thread.start()
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|