print("Connected. Now chatting...") except Exception as e: # Print the exception message print(e) # Exit with a non-zero value, to indicate an error condition exit(1) """ Surround the following code in a try-except block to account for socket errors as well as errors related to user input. Ideally these error conditions should be handled separately. """ try: # Loop until either the server closes the connection or the user requests termination while True: # First, read data from keyboard and send to server bytes_sent = keyboard_to_socket(cli_sock) if bytes_sent == 0: print("User-requested exit.") break # Then, read data from server and print on screen bytes_read = socket_to_screen(cli_sock, srv_addr_str) if bytes_read == 0: print("Server closed connection.") break finally: """ If an error occurs or the server closes the connection, call close() on the connected socket to release the resources allocated to it by the OS. """
cli_sock, cli_addr = srv_sock.accept() cli_addr_str = str(cli_addr) # Translate the client address to a string (to be used shortly) print("Client " + cli_addr_str + " connected. Now chatting...") # Loop until either the client closes the connection or the user requests termination # INNER LOOP FOR DATA EXCHANGE while True: # First, read data from client and print on screen bytes_read = socket_to_screen(cli_sock, cli_addr_str) if bytes_read == 0: print("Client closed connection.") break # Then, read data from user and send to client bytes_sent = keyboard_to_socket(cli_sock) #Returns none if successful, this is only here to check if it has been set to 0 if bytes_sent == 0: print("User-requested exit.") break finally: """ If an error occurs or the client closes the connection, call close() on the connected socket to release the resources allocated to it by the OS. """ cli_sock.close() # Close the server socket as well to release its resources back to the OS srv_sock.close() # Exit with a zero value, to indicate success