Untitled
unknown
plain_text
a year ago
2.3 kB
3
Indexable
Never
import socket import threading import pickle SERVER_IP = '127.0.0.1' SERVER_PORT = 5050 clients = [] def broadcast(client_socket, recv_msg, sender_socket): for client in clients: if client != sender_socket: try: client.send(recv_msg) except Exception as e: print(f"ERROR IN BROADCASTING TO {client} WITH ERROR {e}") remove_client(client) def handle_client(client_socket, client_addr, sender_socket): try: while True: recv_msg = client_socket.recv(2048) if recv_msg: recv_obj = pickle.loads(recv_msg) print(recv_obj) if len(clients) > 1: # broadcast_thread = threading.Thread(target=broadcast, # args=(client_socket, recv_msg,sender_socket )) # broadcast_thread.start() broadcast(client_socket, recv_msg, sender_socket) else: pass except ConnectionResetError as e: print(f"Connection with {client_addr} forcibly closed by the remote host.") remove_client(client_socket) except Exception as e: print(e) def remove_client(client_socket): clients.remove(client_socket) def run_server(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((SERVER_IP, SERVER_PORT)) server.listen() print(f'SERVER STARTED RUNNING ON {SERVER_IP}') while True: try: client_socket, client_addr = server.accept() print(f"NEW CONNECTIONS FROM {client_addr[0]}") sender_socket = client_socket clients.append(client_socket) client_thread = threading.Thread(target=handle_client, args=(client_socket, client_addr, sender_socket)) client_thread.start() except Exception as e: print('error in run_server') run_server()