forked from BinniesLite/networking_final_project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
332 lines (268 loc) · 13.3 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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import socket
import threading
import time
import signal
# Flag to control server loop
running = True
def broadcast(message):
for client in clients:
client.send(message)
def broadcast_group(message, group_id):
for client in group_users[group_id]:
client.send(message)
def handle_client(client):
global running
while running:
try:
global username
username = ""
message = client.recv(1024).decode('utf-8')
if message:
# remove everything before the % character
tokens = message.split("%", 1)
message = "%" + tokens[1]
command = message.split(' ')[0]
temp = []
# Handle empty string
message = message.split(' ')
for msg in message[1:]:
if msg != "":
temp.append(msg)
message = [command] + temp
if command == '%join':
username = message[1]
if username in usernames.values():
client.send('Username already exists. Choose another.\n'.encode('utf-8'))
else:
usernames[client] = username
broadcast(f'{username} has joined the chat room!\n'.encode('utf-8'))
for msg in messages[-2:]:
client.send(msg.encode('utf-8'))
user_list = "\n".join(usernames.values())
client.send(f"Users in the group:\n{user_list}\n".encode('utf-8'))
# handle %connect command
elif command == '%connect':
address_port = message[1:]
if len(address_port) == 2:
try:
new_host = address_port[0]
new_port = int(address_port[1])
client.close()
new_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_client.connect((new_host, new_port))
client.send(f'Connected to specified address {new_host} and port {new_port}.\n'.encode('utf-8'))
except Exception as e:
client.send(f'Error connecting: {str(e)}'.encode('utf-8'))
else:
client.send('Invalid command format. Use "%connect [address] [port]\n".'.encode('utf-8'))
# handle %post command
elif command == "%post":
subject = message[1]
content = " ".join(message[2:])
sender = usernames[client]
# Get current timestamp
post_date = time.strftime('%Y-%m-%d %H:%M:%S')
# Message format updated to include timestamp
full_message = f"Message ID: {len(messages) + 1}, Sender: {sender}, Post Date: {post_date}, Subject: {subject}, Content:{content}\n"
messages.append(full_message)
broadcast(full_message.encode('utf-8'))
# handle %users command
elif command == '%users':
user_list = "\n".join(usernames.values())
client.send(f"Users in the group:\n{user_list}\n".encode('utf-8'))
# handle %leave command
elif command == '%leave':
if client in usernames:
username = usernames[client]
broadcast(f'{username} has left the chat room!\n'.encode('utf-8'))
del usernames[client]
clients.remove(client)
client.send("You left the chat room!\n".encode('utf-8'))
# handle %message command
elif command == '%message':
msg_id = int(message[1])
if 1 <= msg_id <= len(messages):
client.send(messages[msg_id - 1].encode('utf-8'))
else:
client.send("Invalid message ID.\n".encode('utf-8'))
# handle %exit command
elif command == '%exit':
if username is False:
username = ""
if username in usernames:
username = usernames[client]
client.send(f'{username} has left the chat room!\n'.encode('utf-8'))
broadcast(f'{username} has left the chat room!\n'.encode('utf-8')) #added
del usernames[client]
client.send("You are disconnected from the server!\n".encode('utf-8'))
client.send("exit".encode("utf-8"))
client.close()
break
# handle %groups command
elif command == "%groups":
response = f"Here are all the groups available: \n {' '.join([str(i) for i in range(GROUPS)])}"
client.send(response.encode("utf-8"))
# handle %groupjoin command
elif command == "%groupjoin":
# check if user enters arguments that are non-numbers
if (message[1].isnumeric()) is False:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
# check if message length is not valid
if len(message) < 2:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
group_id = int(message[1])
if not (0 <= group_id <= GROUPS):
client.send("Invalid group number".encode("utf-8"))
continue
if client in group_users[group_id]:
client.send(f"Users with id {group_id} exist".encode("utf-8"))
continue
group_users[group_id].append(client)
username = "Jane"
if client in usernames:
username = usernames[client]
client.send(f"User {username} joined group {group_id}\n".encode("utf-8"))
broadcast_group(f"User {username} joined group {group_id}\n".encode("utf-8"), group_id)
# handle %groupusers command
elif command == "%groupusers":
if len(message) < 2:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
group_id = int(message[1])
response = []
if not (0 <= group_id <= GROUPS):
client.send("Invalid group number".encode("utf-8"))
continue
for user in group_users[group_id]:
response.append(usernames[user])
content = "\n".join([res for res in response])
client.send(f"The users in group {group_id} are: {content}\n".encode("utf-8"))
# handle %grouppost command
elif command == "%grouppost":
if len(message) <= 2:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
if not message[1].isnumeric():
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
group_id = int(message[1])
subject = message[2]
content = " ".join(message[3:])
if client not in group_users[group_id]:
client.send("You don't have permission to post in this group".encode("utf-8"))
continue
if not (0 <= group_id <= GROUPS):
client.send("Invalid group number".encode("utf-8"))
continue
sender = ""
if client in usernames:
sender = usernames[client]
# Get current timestamp
post_date = time.strftime('%Y-%m-%d %H:%M:%S')
# Message format updated to include timestamp
full_message = f"Message ID: {len(group_messages[group_id]) + 1}, Sender: {sender}, Post Date: {post_date}, Subject: {subject}, Content:{content}\n"
group_messages[group_id] += [full_message]
broadcast_group(full_message.encode('utf-8'), group_id)
# handle %groupleave command
elif command == "%groupleave":
# check if user enters arguments that are non-numbers
if (message[1].isnumeric()) is False:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
group_id = int(message[1])
if client not in group_users[group_id]:
client.send("You don't have permission to post in this group.\n".encode("utf-8"))
continue
broadcast_group(f"{usernames[client]} left group {group_id}".encode("utf-8"), group_id) #added
# client.send(f"{usernames[client]} left group {group_id}".encode("utf-8"))
group_users[group_id].remove(client)
print(group_users[group_id])
# handle %groupmessage command
elif command == "%groupmessage":
# check if user enters arguments that are non-numbers
if (message[1].isnumeric()) is False:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
if len(message) <= 2:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
continue
group_id = int(message[1])
msg_id = int(message[2])
if client not in group_users[group_id]:
client.send(f"User is not authorized to access message\n".encode('utf-8'))
continue
if 1 <= msg_id <= len(group_messages[group_id]):
client.send(group_messages[group_id][msg_id - 1].encode('utf-8'))
else:
client.send("Invalid message ID.\n".encode('utf-8'))
# handle unknown command
else:
client.send('Invalid command format. Try again!\n'.encode('utf-8'))
except Exception as e:
print(f'Exception occurred in server: {e}')
break
# end handle_client
# Function to handle SIGINT
def signal_handler(sig, frame):
global running
print("\nServer is shutting down...")
running = False
server.close()
for client in clients:
client.close()
print("Server shutdown complete.")
def run_server():
global running
print("Server started. Waiting for connections...")
while running:
try:
client, address = server.accept()
clients.append(client)
print(f'Connection established with {address}')
client.send(welcome_message.encode('utf-8'))
thread = threading.Thread(target=handle_client, args=(client,))
thread.start()
except OSError:
# This exception will be raised when the server socket is closed
break
if __name__ == "__main__":
host = 'localhost'
port = 6789
# "server provides a list of 5 groups"
GROUPS = 5
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = [] # List to keep track of clients
usernames = {} # client -> username
messages = [] # messages
group_messages = {} # group -> messages
group_users = {} # group -> client
for i in range(GROUPS):
group_users[i] = []
group_messages[i] = []
# Define welcome message outside the loop
welcome_message = """
Welcome to the chat room!
Available commands:
%connect [address] [port]: Connect to a different server
%join [username]: Join with the username
%post [subject] [content]: Post a message
%users: Get the list of users in the group
%message [message ID]: Retrieve the content of a message
%leave: Leave the group
%exit: Exit the client program
---------------------------------------------------------
Available group commands:
%groups: Show all groups availables
%groupjoin [group ID]: Join a group with ID 1-5
%grouppost [group ID] [subject] [content]: Post to the group with that id
%groupusers [group ID]: Retrieve a list of users in the given group
%groupmessage [group ID] [message ID]: retrieve the content of an earlier post if you belong to that group
%groupleave [group ID]: Leave the current group if client is in that group
"""
# Register the signal handler
signal.signal(signal.SIGINT, signal_handler)
run_server()