-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
88 lines (61 loc) · 1.99 KB
/
server.py
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
#!/usr/bin/env python3
"""
SERVER DE CHAT CIFRADO E2E
"""
import socket as s
import threading as th
import ssl
def client_thread(client_socket, clients, usernames):
username = client_socket.recv(1024).decode()
usernames[client_socket] = username
print(f"\n[+] El usuario {username} se ha conectado al chat")
for client in clients:
if client is not client_socket:
client.sendall(
f"\n[+] El usuario {username} se ha conectado al chat\n\n".encode()
)
while True:
try:
message = client_socket.recv(1024).decode()
if not message:
break
if message == "!usuarios":
client_socket.sendall(
f"\n[i] Usuarios conectados: {', '.join(usernames.values())}\n\n".encode()
)
continue
for client in clients:
if client is not client_socket:
client.sendall(message.encode())
except:
break
client_socket.close()
clients.remove(client_socket)
del usernames[client_socket]
def server_program():
host = 'localhost'
port = 1234
server_socket = s.socket(s.AF_INET, s.SOCK_STREAM)
server_socket.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1) # TIME_WAIT
server_socket.bind((host, port))
server_socket = ssl.wrap_socket(
server_socket, keyfile='server-key.key',
certfile='server-cert.pem', server_side=True
)
server_socket.listen()
print(f"\n[+] Server está en escucha...")
clients = []
usernames = {}
while True:
client_socket, addr = server_socket.accept()
clients.append(client_socket)
print(f"\n[+] Conectado a {addr}")
thread = th.Thread(
target=client_thread,
args=(client_socket, clients, usernames)
)
thread.daemon = True
thread.start()
server_socket.close()
if __name__ == '__main__':
server_program()