-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver10_Screen.py
339 lines (296 loc) · 12.8 KB
/
server10_Screen.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
import socket
import select
import threading
import sys
import time
import sqlite3
import Queue
# ============ SYS ARG =============
if(len(sys.argv) < 2):
print "Usage: python server.py server_port "
sys.exit()
PORT = int(sys.argv[1])
# ==================================
class Server(object):
def __init__(self):
self.SOCKS = [] # List of active socket connection
self.SOCK_NAME = {} # Dict of login status of users
self.CreateSocket()
self.ConnectToDataBase()
self.CreateThreads()
time.sleep(0.1)
# Initialize server listening socket
def CreateSocket(self):
self.SERV_SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.SERV_SOCK.bind(("0.0.0.0", PORT))
self.SERV_SOCK.listen(10)
print "[000] Server on port %d" % PORT
def ConnectToDataBase(self):
try:
self.con = sqlite3.connect("user.sqlite3")
self.cur = self.con.cursor()
# con.commit()
# con.close()
print '[008]Connect to Database'
except Exception, emsg:
print '[461]DataBase Error', str(emsg)
# Create All Threads needed
def CreateThreads(self):
# Handle New Connection
self.T_NewCon = threading.Thread(target=self.NewConnection, args=())
self.T_NewCon.setDaemon(True)
self.T_NewCon.start()
# Sender
self.T_Sender = threading.Thread(target=self.CreateSender, args=())
self.T_Sender.setDaemon(True)
self.T_Sender.start()
# Receiver
self.T_Receiv = threading.Thread(target=self.CreateReceiv, args=())
self.T_Receiv.setDaemon(True)
self.T_Receiv.start()
# Thread Accept new connection and append to self.SOCKS List
def NewConnection(self):
print '[001] New connection thread start'
while True:
sockfd, addr = self.SERV_SOCK.accept()
self.SOCKS.append(sockfd)
print "[005] Got connection from %s" % str(addr)
# Thread Send messages in Message_Send_Queue
def CreateSender(self):
print '[002] Sender thread start'
self.Send_Queue = Queue.Queue()
while True:
try:
if not self.Send_Queue.empty():
Fetch = self.Send_Queue.get()
Message = Fetch['Message']
sock = Fetch['Destination']
print '[Snd]' + Message
sock.send(Message)
else:
time.sleep(0.1) # Empty Queue
except Exception, emsg:
print '[430] Sender', str(emsg)
self.Remove_User_Chat(sock=self.SOCK_NAME[sock])
self.Remove_User_Login(sock)
self.Broacast_UserList()
self.Remove_Connection(sock)
print '[439] Sender down'
return
# Thread Receive message from self.SOCK_NAME.keys() and Put to Message_Recv_Queue
def CreateReceiv(self):
print '[003] Receive thread start'
self.Recv_Queue = Queue.Queue()
while True:
try:
rlist, wlist, xlist = select.select(self.SOCK_NAME.keys(), [], [], 1)
for sock in rlist:
Message = sock.recv(512)
print '[Rcv]' + Message
if not Message:
# Assume connection broken if recv empty msg
raise IOError
else:
# Put Message into Recv Queue
self.Put_to_Recv_Queue(sock, Message)
except Exception:
print '[440] Receiver Exception, Removing User'
self.Remove_User_Chat(sock=sock)
self.Remove_User_Login(sock)
self.Broacast_UserList()
self.Remove_Connection(sock)
print '[449] Receiver down'
# Utility Verify Login
def VerifyUser(username, password):
try:
pass
# do sql query
# If yes
return True
# If no
# return False
except Exception, emsg:
print '[DB8]'+str(emsg)
return False
# Utility Broadcast message
def Broadcast(self, message):
for s in self.SOCK_NAME.keys():
self.Put_to_Send_Queue(s, message)
# Utility Construct Message to Send
def Put_to_Send_Queue(self, sock, message):
try:
Pair = {}
Pair['Destination'] = sock
Pair['Message'] = message
self.Send_Queue.put(Pair)
except Exception, emsg:
print "[410] Put_to_Send_Queue %s" % str(emsg)
# Utility Construct Message received
def Put_to_Recv_Queue(self, sock, message):
try:
Pair = {}
Pair['Source'] = sock
Pair['Message'] = message
self.Recv_Queue.put(Pair)
except Exception, emsg:
print "[410] Put_to_Recv_Queue %s" % str(emsg)
# Utility Construct current UserList
def Get_UserList(self):
UserList = ''
for username in self.SOCK_NAME.values():
UserList = UserList + username + ' '
return UserList
# Utility Broadcast current UserList
def Broacast_UserList(self):
s = self.Get_UserList()
self.Broadcast("[202]"+s)
# Utility Get socket by user name from {sock, username} pair
def Get_Sock_By_Name(self, name):
for sock, username in self.SOCK_NAME.items():
if username == name:
return sock
return None
# Utulity Remove user from all users' Chat List
def Remove_User_Chat(self, name=None, sock=None):
if name is not None:
self.Broadcast('[215]'+name)
time.sleep(0.2)
if sock is not None:
if sock in self.SOCK_NAME.keys():
self.Broadcast('[215]'+self.SOCK_NAME[sock])
time.sleep(0.2)
# Utility Remove a user from SOCK_NAME
def Remove_User_Login(self, sock):
if sock in self.SOCK_NAME.keys():
name = self.SOCK_NAME[sock]
self.SOCK_NAME.pop(sock)
print "[102] %s User Removed" % name
else:
print "[103] User Not Exist"
# Utility Remove a connection
def Remove_Connection(self, sock):
if sock in self.SOCKS:
self.SOCKS.remove(sock)
print "[100] Connection Removed"
else:
print "[101] Connection Not Exist"
# Main Loop, Fetch message From Message_Recv_Queue and Handle them
def MainLoop(self):
print '[004] MainLoop Main thread start'
while True:
try:
if not self.Recv_Queue.empty():
Fetch = self.Recv_Queue.get()
sock = Fetch['Source']
Message = Fetch['Message']
Header = Message[0:5]
# Login Request
if '[300]'in Header:
Pos = Message.index(':')
username = Message[5:Pos]
password = Message[Pos+1:]
if self.VerifyUser(username=username, password=password):
if username in self.SOCK_NAME.values():
self.Put_to_Send_Queue(sock, "[402]User already Loged in")
print "[104] User already Loged in"
else:
self.SOCK_NAME[sock] = username
self.Put_to_Send_Queue(sock, "[201]Login SUCCESS")
time.sleep(0.5) # Avoid 2 Msg Arrive At Same Time
self.Broacast_UserList()
print "[105] Login as %s" % username
print "[106] Users", self.SOCK_NAME.values()
else:
self.Put_to_Send_Queue(sock, "[409]Username or Password Wrong")
# Chat Signals are [31X], From 310 to 315
elif '[31' in Header:
# Chat Request
if '[310]' in Header:
Callee = (Message[5:]).rstrip().lstrip()
Callee_sock = self.Get_Sock_By_Name(Callee)
Caller = self.SOCK_NAME[sock]
Caller_sock = sock
print '[DB6]', Caller
print '[DB7]', Callee
if Callee_sock is not None:
self.Put_to_Send_Queue(Caller_sock, '[210]Chat Req Sent')
self.Put_to_Send_Queue(Callee_sock, '[211]'+Caller)
else:
self.Put_to_Send_Queue(Caller_sock, '[405]Peer Offline')
# Chat Invite Refused
elif '[311]' in Header:
Caller = (Message[5:]).rstrip().lstrip()
Caller_sock = self.Get_Sock_By_Name(Caller)
Callee = self.SOCK_NAME[sock]
if Caller_sock is not None:
self.Put_to_Send_Queue(Caller_sock, '[212]'+Callee)
else:
print '[411]Peer Not Exits'
# Chat Invite Accepted
elif '[312]' in Header:
Caller = (Message[5:]).rstrip().lstrip()
Caller_sock = self.Get_Sock_By_Name(Caller)
Callee = self.SOCK_NAME[sock]
Callee_sock = sock
if Caller_sock is not None:
self.Put_to_Send_Queue(Caller_sock, '[213]'+Callee)
self.Put_to_Send_Queue(Callee_sock, '[213]'+Caller)
else:
print '[412]Peer Not Exits'
# Chat Msg
elif '[313]' in Header:
Pos = Message.index(':')
Content = Message[Pos:]
PeerName = (Message[5:Pos]).rstrip().lstrip()
Peer_sock = self.Get_Sock_By_Name(PeerName)
From = self.SOCK_NAME[sock]
if Peer_sock is not None:
self.Put_to_Send_Queue(Peer_sock, '[214]'+From+Content)
else:
self.Put_to_Send_Queue(sock, '[215]'+PeerName)
print '[413]Peer Not Exits'
# Chat Terminate Request
elif '[314]' in Header:
PeerName = (Message[5:]).rstrip().lstrip()
Peer_sock = self.Get_Sock_By_Name(PeerName)
From = self.SOCK_NAME[sock]
if Peer_sock is not None:
self.Put_to_Send_Queue(Peer_sock, '[215]'+From)
else:
print '[414]Peer Not Exits'
# Chat File Transmit Request
elif '[315]' in Header:
pass
# User List Query
elif '[350]' in Header:
s = self.Get_UserList()
self.Put_to_Send_Queue(sock, "[202]"+s)
# Broadcast Request
elif '[360]'in Header:
Message = Message[5:]
userFrom = '<%s>' % str(self.SOCK_NAME[sock])
self.Broadcast('[205]'+userFrom+Message)
# Connection Alive Query
elif '[370]' in Header:
self.Put_to_Send_Queue(sock, "[204]Connection alive")
# User Logout
elif '[390]' in Header:
name = Message[5:]
self.Remove_User_Chat(name=name, sock=sock)
self.Remove_User_Login(sock)
time.sleep(0.1) # Corwded Broadcast
self.Broacast_UserList()
# Undefined command
else:
self.Put_to_Send_Queue(sock, "[404]Undefined command")
else:
time.sleep(0.1)
except KeyboardInterrupt, emsg:
print "[-] Main Loop KeyboardInterrupt"
self.con.close()
sys.exit()
except Exception, emsg:
print "[-] Main Loop %s" % str(emsg)
# Main()
S1 = Server()
S1.MainLoop()