def listen_for_data(c): while True: try: sender, message = pickle.loads(c.recv(1024)) if not perform_command(c, message) and len(message) > 0: print(f"{sender.name}: {message}") broadcast(sender, message) except ConnectionResetError: p = clients.pop(c, Participant.Bot("Someone")) print(f"{p.name} left the server") broadcast(Participant.Person("server"), f"{p.name} left the chat!") c.close() break except ConnectionAbortedError: break
print( "To start a server that should connect to specified ip and port:\n" "$python3 server.py <u>ip</u> <u>port</u>") sys.exit() port = int(sys.argv[2]) except (IndexError, ValueError): print( "IP and port must be specified. Correct usage e.g $py server.py localhost 2410" ) sys.exit() server = socket.socket() server.bind((ip, port)) server.listen() host = Participant.Person("Host") clients = {} print("Server is running...") # broadcast to all clients: def broadcast(sender, message): for c in clients: data = pickle.dumps((sender, message)) c.send(data) # constantly listen if any clients has sent any data: def listen_for_data(c):
"> Example usage (connecting as a bot (Alice) to localhost:2410):\n" ">> $python3 client.py localhost 2410 alice") sys.exit() port = int(sys.argv[2]) except (IndexError, ValueError): print( "IP and port must be specified. Correct usage e.g $py client.py localhost 2410" ) sys.exit() # Define the participant: try: participant = \ available_bots[sys.argv[3].lower()] \ if len(sys.argv) == 4 \ else Participant.Person(input("Choose a nickname: ")) except KeyError: print( f"Sorry, cannot summon {sys.argv[3]} :( but you could try one of these bots:\n" f"{list(available_bots.keys())}") sys.exit() if isinstance(participant, Participant.Batman): who = participant.ACTIONS['who'] identify = participant.ACTIONS['identify'] # Start the TCP connection: client = socket.socket() try: client.connect((ip, port)) except ConnectionRefusedError: