-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
161 lines (126 loc) · 4.81 KB
/
server.py
File metadata and controls
161 lines (126 loc) · 4.81 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import socket
import threading
import ssl
import time
from protocol import send_json, recv_json
from encryption_utils import generate_key
HOST = "0.0.0.0"
PORT = 5000
clients = {}
user_sockets = {}
rooms = {}
lock = threading.Lock()
stats = {
"messages": 0,
"files": 0,
"connections": 0
}
def broadcast_room(room, message, exclude=None):
if room in rooms:
for client in rooms[room]:
if client != exclude:
try:
send_json(client, message)
except:
remove_client(client)
def remove_client(client):
with lock:
username = clients.get(client)
if username:
print(f"{username} disconnected")
user_sockets.pop(username, None)
clients.pop(client, None)
for room in rooms.values():
if client in room:
room.remove(client)
client.close()
def handle_client(client):
buffer = ""
while True:
try:
messages, buffer = recv_json(client, buffer)
for data in messages:
msg_type = data.get("type")
if msg_type == "join":
username = data["username"]
room = data["room"]
with lock:
clients[client] = username
user_sockets[username] = client
if room not in rooms:
rooms[room] = []
rooms[room].append(client)
send_json(client, {"type": "info", "message": f"Joined {room}"})
broadcast_room(room, {"type": "info", "message": f"{username} joined"}, client)
elif msg_type == "message":
stats["messages"] += 1
room = data["room"]
username = clients.get(client)
broadcast_room(room, {
"type": "message",
"sender": username,
"content": data["content"]
})
elif msg_type == "private":
to_user = data["to"]
if to_user in user_sockets:
send_json(user_sockets[to_user], {
"type": "private",
"from": clients[client],
"content": data["content"]
})
elif msg_type == "secret":
to_user = data["to"]
if to_user in user_sockets:
send_json(user_sockets[to_user], {
"type": "secret",
"from": clients[client],
"content": data["content"]
})
elif msg_type == "file":
stats["files"] += 1
filename = data["filename"]
filesize = data["filesize"]
room = data["room"]
username = clients.get(client)
broadcast_room(room, {
"type": "file",
"filename": filename,
"filesize": filesize,
"from": username
}, client)
remaining = filesize
while remaining > 0:
chunk = client.recv(min(4096, remaining))
remaining -= len(chunk)
for member in rooms[room]:
if member != client:
try:
member.sendall(chunk)
except:
remove_client(member)
except Exception as e:
print("Client error:", e)
break
remove_client(client)
def monitor():
while True:
print(f"[STATS] Clients: {len(clients)} | Messages: {stats['messages']} | Files: {stats['files']}")
time.sleep(10)
def start_server():
generate_key()
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(5)
print("Server running with SSL...")
threading.Thread(target=monitor, daemon=True).start()
while True:
client, addr = server.accept()
secure_client = context.wrap_socket(client, server_side=True)
print(f"Connection from {addr} | Cipher: {secure_client.cipher()}")
stats["connections"] += 1
threading.Thread(target=handle_client, args=(secure_client,), daemon=True).start()
if __name__ == "__main__":
start_server()