-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
73 lines (58 loc) · 2.22 KB
/
client.py
File metadata and controls
73 lines (58 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import socket
import threading
from crypto_utils import encrypt_message, decrypt_message
class ChatClient:
def __init__(self, host='localhost', port=5000):
self.host = host
self.port = port
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.encryption_key = None
def connect(self):
try:
self.client_socket.connect((self.host, self.port))
self.encryption_key = self.client_socket.recv(4096)
print(f"Connesso al server {self.host}:{self.port}")
return True
except Exception as e:
print(f"Errore di connessione: {e}")
return False
def start(self):
if not self.connect():
return
receive_thread = threading.Thread(target=self.receive_messages)
receive_thread.daemon = True
receive_thread.start()
self.send_messages()
def receive_messages(self):
while True:
try:
encrypted_message = self.client_socket.recv(4096).decode()
if not encrypted_message:
break
message = decrypt_message(encrypted_message, self.encryption_key)
print(f"\nMessaggio ricevuto: {message}")
except Exception as e:
print(f"Errore nella ricezione: {e}")
break
self.disconnect()
def send_messages(self):
while True:
try:
message = input("> ")
if message.lower() == 'quit':
break
encrypted_message = encrypt_message(message, self.encryption_key)
self.client_socket.send(encrypted_message.encode())
except Exception as e:
print(f"Errore nell'invio: {e}")
break
self.disconnect()
def disconnect(self):
try:
self.client_socket.close()
except:
pass
print("\nDisconnesso dal server")
if __name__ == "__main__":
client = ChatClient()
client.start()