def forward(my_socket, username, msg): for th in running_thread: try: if (th.socket != my_socket): ml.strSend(th.socket, username + "> " + msg) except: console_print(th.socket, "non ha ricevuto")
def send_to_all(my_socket, username, msg): for socket in connessioni: try: if(socket != my_socket): ml.strSend(socket, username + "> " + msg) except: print(socket, "non ha ricevuto")
def run(self): try: while True: msg = ml.strReceive(self.s) # Ricezione messaggio now = datetime.now().strftime("%d-%m-%Y %H:%M:%S") # Data corrente # Comando di uscita, il thread viene terminato if msg == 'quit': out = "["+now+"] " + self.username + " ha abbandonato la chat" print(out) ml.strSend(self.s, out) # Messaggio di termine send_to_all(self.s, self.username, out) self.s.close() connessioni.remove(self.s) break; print("["+now+"]", self.username + ": " + msg) send_to_all(self.s, self.username, msg) except ConnectionResetError: # Nel caso il client venga chiuso dalla X client_closed(self.s, self.username) except ValueError: # Nel caso il client venga chiuso dalla X client_closed(self.s, self.username)
# Creazione socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Client connesso a", ml.HOST) # # Connessione a HOST e PORT # clientSocket.connect((ml.HOST, ml.PORT)) print("Connesso al server", ml.HOST, ":", ml.PORT) # # Inserimento username # username = input("Username: "******"") if (len(msg) != 0): # Verifica se il messaggio è vuoto # Invio del messaggio ml.strSend(clientSocket, msg)
def client_quitted(my_socket, username): out = "[" + timespamp() + "] " + username + " ha abbandonato la chat" print(out) console_print(out) ml.strSend(my_socket, out) # Messaggio di termine forward(my_socket, username, out)
# # testClient for ServerOne # Team: Sandro Gallo # last-updated: 10/04/2020 by Sandro # import socket import mylib as ml # Create a socket object (client) clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Request a message to user msg = input("Enter a message to send to the server: ") # Try to connect to the server clientSocket.connect((ml.HOST, ml.PORT)) print("Connected to server", ml.HOST, ":", ml.PORT) # Send a message to the server ml.strSend(clientSocket, msg) print("Message sent") # Close the socket when done clientSocket.close() print("Connection closed.") input("press RETURN to terminate")