Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.6 kB
6
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):
#     global clients
#     for c in clients:
#         if c != sender_socket:
#             try:
#                 c.send(recv_msg)
#             except Exception as e:
#                 print(f'ERROR IN SENDING DATA TO {client_socket}')
#                 remove_client(c)
#         else:
#             print(f"CANNNOT SEND TO {c}")    
            
def broadcast(client_socket, recv_msg , sender_socket):
    global clients
    for c in clients:
        try:
            c.send(recv_msg)
        except Exception as e:
            print(e)
        




def handle_client(client_socket, client_addr, sender_socket):
    
    try:
        while True:
            recv_msg = client_socket.recv(2048)
            
            
            if recv_msg is not None:
                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:
                print(f'UNABLE TO RECEIVE MESSAGE FROM {client_socket}')
    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()