-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
159 lines (133 loc) · 4.23 KB
/
server.py
File metadata and controls
159 lines (133 loc) · 4.23 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
from socket import socket, AF_INET, SOCK_STREAM
from threading import Thread
from datetime import datetime
HOST = "127.0.0.1" # Enter your server's IP
PORT = 32500
MAX_USERS = 100
BUFFER_SIZE = 1024
clients = {}
addresses = {}
SOCK = socket(AF_INET, SOCK_STREAM)
SOCK.bind((HOST, PORT))
# Security
def isSpam(msg, IP):
is_spam = True
msg_str = ""
try:
msg_str = msg.decode("utf8")
except:
print(f"[Security] Couldn't decode the message ({IP})")
return is_spam
if msg_str.strip() == "": # is Empty
print(f"[Security] Empty message ({IP})")
elif len(msg_str) >= BUFFER_SIZE:
print(f"[Security] Overly long message ({IP})")
else:
is_spam = False
return is_spam
def verifyClient(msg_b, IP):
try:
msg_str = msg_b.decode("utf8")
except:
print(f"[Security] Couldn't decode the message ({IP})")
return False
if msg_str == "CHAT":
return True
else:
print(f"[Security] Client verification failed ({IP})")
return False
# Connectivity
def closeConnection(conn):
if conn in clients:
del clients[conn]
try:
conn.send("/quit".encode("utf8"))
conn.close()
except:
pass
def broadcast(msg_str):
print(f"[Broadcast] {msg_str}")
msg = bytes(msg_str+'\n',"utf8")
try: # Fixes server crashes
for sock in clients:
sock.send(msg)
except:
pass
def log(msg, type="Info"):
now = datetime.now().strftime("[%H:%M:%S]")
print(f"[{type}][{now}] {msg}")
# Submain server function
def handleClient(conn, address):
# Receive and check
while True:
conn.send("Enter your nickname:\n".encode("utf8"))
try:
name = conn.recv(BUFFER_SIZE)
except:
print(f"[Security] Couldn't receive the message ({address[0]})")
closeConnection(conn)
return
if isSpam(name, address[0]):
closeConnection(conn)
return
# Process the first request
name = name.decode("utf8")
if name == "/quit":
closeConnection(conn)
print(f"[Info] {address[0]}:{address[1]} has left the chat")
return
# Check for a similar name
if name in clients.values():
print(f"[Info] Duplicate name found ({name})")
conn.send("Nickname taken\n".encode("utf8"))
continue
else:
clients[conn] = name
break
print(f"[Info] {address[0]}:{address[1]} chose username \"{name}\"")
msg = f"{name} has joined the chat"
broadcast(msg)
# Keep processing requests
while True:
# Receive and check
try:
msg = conn.recv(BUFFER_SIZE)
except:
print(f"[Security] Couldn't receive the message ({address[0]})")
closeConnection(conn)
return
if isSpam(msg, address[0]):
closeConnection(conn)
return
# Handle the message
msg = msg.decode("utf8")
if msg == "/quit":
closeConnection(conn)
broadcast(f"{name} has left the chat")
break
now = datetime.now().strftime("[%H:%M:%S]")
broadcast(f"{name} {now}: "+ msg)
# Main server function
def acceptIncomingConnections():
while True:
conn, address = SOCK.accept()
# Verify
try:
header = conn.recv(BUFFER_SIZE)
except:
print(f"[Security] Couldn't receive the message ({address[0]})")
closeConnection(conn)
continue
if not verifyClient(header, address[0]):
closeConnection(conn)
continue
# Start the loop
print(f"[Info] {address[0]}:{address[1]} has connected")
addresses[conn] = address
Thread(target=handleClient, args=(conn, address)).start()
SOCK.listen(MAX_USERS)
print(f"Chat Server is running at {HOST}:{PORT}")
accept_connections = Thread(target=acceptIncomingConnections)
accept_connections.start()
accept_connections.join()
SOCK.close()