-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
377 lines (312 loc) · 12.2 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
from threading import Thread
import socket
import sched
import time
import pickle
import copy
HEADER_SIZE=10
def accept():
while 1:
client_socket,client_addr = server_socket.accept() #threads are just created for making blocks of code execute parallely! like accepting the connections and handling clients all these work in parallel
print("A client has been connected to the server")
Thread(target=initialize,args=(client_socket,True)).start()
def details(c):
try:
global groupinfo
groupobject={}
for x,y in groupinfo.items():
groupobject[x]=list([y[1],y[2],len(y[3])])
messageobj=pickle.dumps(groupobject)
message="details"+str(len(messageobj))
message=message.encode('UTF-8')
c.sendall(f"{len(message):<{HEADER_SIZE}}".encode('UTF-8')+message)
c.sendall(messageobj)
return 1
except Exception as e:
print("Exception occured in ddetails: "+str(e))
# def members(c):
# global groupinfo,clientinfo
# sep='*****seperator*****'
# m="$$$length$$$"+"!!!!!separator!!!!!"
# for x,y in groupinfo.items():
# m+=x+sep+str(len(y[3]))+"!!!!!separator!!!!!"
# #print("from server, this is m"+ str(m))
# m=m.encode("ASCII")
# c.sendall(m)
# return 1
def initialize(c,check):
global clientinfo
try:
if check==True:
mess_len=c.recv(HEADER_SIZE).decode('UTF-8')
name=c.recv(int(mess_len)).decode('UTF-8')
print("initialize: "+name)
clientinfo[c]=[name]
else:
print("logged out : ")
d=1
while(d):
header=c.recv(HEADER_SIZE).decode('UTF-8')
m=c.recv(int(header)).decode('UTF-8')
if(m=="groups"): #Gui part should send a message,
d=details(c)
elif(m=="create"):
d=create(c)
elif(m=="join"):
d=join(c)
elif(m=="QUIT"):
m="BYE".encode('UTF-8')
header=f"{len(m):<{HEADER_SIZE}}".encode('UTF-8')
c.sendall(header+m)
c.close()
break
except Exception as e:
if check==True:
print("exception in initialize: "+str(e))
else:
print("exception after logging out: "+str(e))
c.close()
def create(c):
global clientinfo, groupinfo,eventslist,groupMessages
try:
print("create")
length=c.recv(HEADER_SIZE).decode("UTF-8")
string=c.recv(int(length)).decode('UTF-8')
list1=string.split("*****seperator*****")
print(list1)
groupinfo[list1[0]+list1[3]]=[list1[1],int(list1[2]),len(list1[0]),[clientinfo[c][0]],[c]] #groupinfo=[password,limit,groupcode,[],[]]
groupMessages[list1[0]+list1[3]]=[]
clientinfo[c].append(list1[0]+list1[3])
eventslist[list1[0]+list1[3]]=[]
Thread(target=handling_the_client,args=(c,)).start()
return 0 #return 0 once handling clients is done!
except Exception as e:
print("exception in create: "+str(e))
clientinfo.remove(clientinfo[c])
c.close()
return 0
def join(c):
e=1
print("join")
sep='*****seperator*****'
global clientinfo, groupinfo,eventslist,scheduler,groupMessages
try:
while e:
length=c.recv(HEADER_SIZE).decode("UTF-8")
string=c.recv(int(length)).decode('UTF-8')
name=string.split(sep)[0] #name of the group should be sent concat with code!!
print(name)
password=string.split(sep)[1]
print(password)
grouppassword=groupinfo[name][0]
print(grouppassword + "\t" + password)
obj={}
message="auth"
if name in groupinfo.keys():
if len(groupinfo[name][3])<(groupinfo[name][1]):
print("insdie")
if grouppassword==password:
obj['result']=True
obj['groupfull']=False
messageobj=pickle.dumps(obj)
message=message+str(len(messageobj))
message=message.encode('UTF-8')
header=f'{len(message):<{HEADER_SIZE}}'.encode('UTF-8')
c.sendall(header+message)
c.sendall(messageobj)
print("Sent succesylly")
for x in eventslist[name]:
if x:
scheduler.cancel(x)
eventslist[name].remove(x)
groupinfo[name][3].append(clientinfo[c][0])
groupinfo[name][4].append(c)
print("joined:"+str(groupinfo))
clientinfo[c].append(name)
groupMessages[name].append({
"colour":"#223344",
'message':"{} has joined the chamber!".format(clientinfo[c][0]),
"name":"ChatBot"
})
sendAllmemberslist(name,c)
sendAllMessages(name,c)
broadcasteveryone(name,c)
Thread(target=handling_the_client,args=(c,)).start() #//un comment it , when the chatting window is done!
return 0
elif password!=grouppassword:
obj['result']=False
obj['groupfull']=False
#return 0 once handling clients is done!
else:
obj['result']=False
obj['groupfull']=True
messageobj=pickle.dumps(obj)
message=message+str(len(messageobj))
message=message.encode('UTF-8')
header=f'{len(message):<{HEADER_SIZE}}'.encode('UTF-8')
c.sendall(header+message)
c.sendall(messageobj)
return 1
else:
return 1
except Exception as e:
message="groupdead"
message=message.encode('UTF-8')
header=f'{len(message):<{HEADER_SIZE}}'.encode('UTF-8')
c.sendall(header+message)
print("Exception in join: "+str(e))
return 1
def sendAllmemberslist(name,c):
print("send all members list")
try:
message="membersList"
obj={}
obj["0"]=groupinfo[name][3]
print("memberslist"+str(obj["0"]))
messageobj=pickle.dumps(obj)
message=message+str(len(messageobj))
message=message.encode('UTF-8')
header=f"{len(message):<{HEADER_SIZE}}".encode('UTF-8')
c.sendall(header+message)
c.sendall(messageobj)
except Exception as e:
print("Exception occured in sendAllmembersList: "+str(e))
return
def broadcasteveryone(gname,client):
try:
global clientinfo,groupinfo
message="memberadd"
addobj={'name':clientinfo[client][0], 'message': '{} has joined the chamber!'.format(clientinfo[client][0])}
messageobj=pickle.dumps(addobj)
message=message+str(len(messageobj))
message=message.encode('UTF-8')
header=f"{len(message):<{HEADER_SIZE}}".encode('UTF-8')
for x in groupinfo[gname][4]:
if x!=client:
x.sendall(header+message)
x.sendall(messageobj)
except Exception as e:
print("Exception occured in broadcast everyone: "+str(e))
return
def sendAllMessages(groupname,c):
try:
global groupMessages
oldmessages={'0':groupMessages[groupname]}
print("oldmessages: "+str(oldmessages))
messageobj=pickle.dumps(oldmessages)
message="oldmessages"
message=message+str(len(messageobj))
message=message.encode('UTF-8')
header=f"{len(message):<{HEADER_SIZE}}".encode('UTF-8')
c.sendall(header+message)
c.sendall(messageobj)
except Exception as e:
print("Exception occured in sendAllMessages: "+str(e))
return
# def membersList(client,grouplist):
# sep='*****seperator*****' #groupinfo=[password,limit,groupcode,[],[]]
# groupmembers="$$memlist$$"+sep
# for x in grouplist[3]:
# groupmembers+=x+sep
# #print(groupmembers)
# client.sendall(groupmembers.encode("ascii"))
def handling_the_client(client):
try:
print("handling client")
global clientinfo, groupinfo,groupMessages
while 1:
length=client.recv(HEADER_SIZE).decode('UTF-8')
#print(length)
message=client.recv(int(length)).decode('UTF-8')
#print(message)
if message[0:7]=="message":
broadcast(clientinfo[client][0],client,groupinfo[clientinfo[client][1]][4],int(message[7:]),True)
elif message=="QUIT":
if len(groupinfo[clientinfo[client][1]][3])==1:
groupinfo[clientinfo[client][1]][3].remove(clientinfo[client][0])
groupinfo[clientinfo[client][1]][4].remove(client)
group_name = clientinfo[client].pop()
print("group details:"+str(groupinfo[group_name]))
Thread(target=scheduling,args=(group_name,)).start()
Thread(target=initialize,args=(client,False)).start()
break
else:
broadcast(clientinfo[client][0],client,groupinfo[clientinfo[client][1]][4],"",False)
groupinfo[clientinfo[client][1]][3].remove(clientinfo[client][0])
groupinfo[clientinfo[client][1]][4].remove(client)
clientinfo[client].pop()
Thread(target=initialize,args=(client,False)).start()
break
except Exception as e:
print("Exception occured in handling client: "+str(e))
return
def broadcast(name,client,memberslist,length,check):
try:
global clientinfo,groupMessages
if check==True:
newmessageobj=pickle.loads(client.recv(length))
#print("broadcast: "+ str(newmessageobj))
groupMessages[clientinfo[client][1]].append(copy.deepcopy(newmessageobj))
messageobj=pickle.dumps(newmessageobj)
message="newmessage"
else:
messageobj=pickle.dumps({
"name":"ChatBot",
"colour":"#223344",
"message":"{} has left the chat".format(name),
"person":name
})
groupMessages[clientinfo[client][1]].append({
"name":"ChatBot",
"colour":"#223344",
"message":"{} has left the chat".format(name)
})
message="membergone"
message=message+str(len(messageobj))
message=message.encode('UTF-8')
header=f"{len(message):<{HEADER_SIZE}}".encode('UTF-8')
print("memberlist:"+str(memberslist))
for x in memberslist:
if x!=client:
x.sendall(header+message)
x.sendall(messageobj)
print("member broadcast done!")
except Exception as e:
print("Exception occured in broadcast: "+str(e))
return
def scheduling(group_name):
try:
global eventslist,scheduler
scheduler = sched.scheduler(time. time, time.sleep)
e1 = scheduler.enter(7, 1, checkgroup,(group_name,))
eventslist[group_name].append(e1)
scheduler.run()
except Exception as e:
print("Exception occured in scheduling: "+str(e))
return
def checkgroup(group_name):
try:
global clientinfo, groupinfo
if len(groupinfo[group_name][3])==0:
groupinfo.pop(group_name)
groupMessages.pop(group_name)
except Exception as e:
print("Exception occured in checkgroup: "+str(e))
return
clientinfo={}
groupinfo={}
eventslist={}
groupMessages={}
scheduler = None
Host=""
port=8000
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind((Host,port))
#print(Host)
if __name__ == "__main__":
server_socket.listen(50)
print("Socket is listening for sockets!!")
main_thread=Thread(target=accept)
main_thread.start() #starts the thread
main_thread.join() #blocks the code here till the main_threads execution doesn't end!
server_socket.close()