-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
104 lines (79 loc) · 2.49 KB
/
client.py
File metadata and controls
104 lines (79 loc) · 2.49 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import socket as s
import threading
import sys
from colors import bcolors
HOST = '127.0.0.1'
PORT = 9999
global authenticated
authenticated = False
def handle_auth(sock):
global authenticated
global user
valid_user = False
try:
while not valid_user:
user = input(f"{bcolors.WHITE}🙂 Digite seu usuário: ")
sock.sendall(str.encode(user))
data = sock.recv(1024).decode()
if data == "valid":
valid_user = True
else:
print(f"{bcolors.FAIL}❌ Usuário já existe ou é inválido. Tente outro.{bcolors.ENDC}")
has_password = sock.recv(1024).decode()
if has_password == "true":
while not authenticated:
password = input(f"{bcolors.WHITE}🔒 Digite a senha: ")
sock.sendall(str.encode(password))
data = sock.recv(1024)
if data.decode() != "authenticated":
print(f"{bcolors.FAIL}❌ Senha incorreta. Tente novamente.")
else:
authenticated = True
authenticated = True
thread = threading.Thread(target=listen_server, args=(sock,))
thread.start()
print(f"{bcolors.OKGREEN}----------- 🌐 Você entrou no chat -----------{bcolors.ENDC}")
except Exception:
print(f"\n{bcolors.FAIL}❌ Erro: não foi possível autenticar.")
sys.exit()
def listen_server(sock):
global authenticated
while authenticated:
try:
data = sock.recv(1024)
print(data.decode())
except Exception as e:
print(e)
break
def start_client():
global user
try:
sock = s.socket(s.AF_INET, s.SOCK_STREAM)
sock.connect((HOST, PORT))
while True:
if not authenticated:
handle_auth(sock)
continue
text = input(f"{bcolors.OKCYAN}")
if text.startswith("/"):
if text == "/q":
raise KeyboardInterrupt
try:
pvd_user, message = text.split(" ", 1)
sock.sendall(str.encode(f"{user}: {pvd_user}-{message}"))
except:
print(f"{bcolors.FAIL}❌ Comando inválido.{bcolors.ENDC}")
else:
sock.sendall(str.encode(f"{user}: {text}"))
except KeyboardInterrupt:
print(f"{bcolors.WARNING}----------- 🌐 Você saiu do chat -----------{bcolors.ENDC}")
except Exception as e:
print(f"{bcolors.FAIL}❌ Erro: {e}{bcolors.ENDC}")
finally:
sock.close()
if __name__ == "__main__":
try:
start_client()
except KeyboardInterrupt:
print(f"\n{bcolors.FAIL}----------- 🌐 Conexão encerrada -----------{bcolors.ENDC}")
sys.exit(0)