-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain.py
351 lines (298 loc) · 9.75 KB
/
Main.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
from registrationWindow import Ui_regWin
from clientWindow import Ui_clientWin
from ChatBox import Ui_chatBox
#from CommWin import Ui_NetWindow
from PyQt5 import QtCore,QtWidgets
import socket
import funcs
import sys
import threading
import queue
sockLock = threading.Lock()
clientSock = ''
hostUserName =''
hostUserNo = ''
hostMacAdress = ''
HOST = '172.16.30.20'
PORT = funcs.PORT
class writingThread(QtCore.QThread):
completeSignal = QtCore.pyqtSignal(str,str,str)
def __init__(self,msg,q,key,parent = None):
super(writingThread,self).__init__(parent)
self.parent = parent
self.key = key
msg = msg.split(' ')
self.fileName = msg[0]
self.senderName = msg[1]
self.q = q
self.f = open(self.fileName,'wb')
print("file "+msg[0]+ " from "+msg[1]+" opened in writing thread")
def __del__(self):
self.wait()
def run(self):
while True:
data = self.q.get()
if data == None:
break
self.f.write(data)
self.f.close()
print("File "+self.fileName+" from "+self.senderName+" completed")
self.completeSignal.emit(self.key,self.fileName,self.senderName)
class readingThread(QtCore.QThread):
sendingCompleteSignal = QtCore.pyqtSignal(str)
def __init__(self,sock,uno,fno,rno,uname,fname,parent = None):
super(readingThread,self).__init__(parent)
self.parent = parent
self.clientSock = sock
self.roomNo = rno
self.fileName = fname
self.hostUserNo = uno
self.fileNo = fno
self.hostUserName = uname
self.f = open(self.fileName,'rb')
with sockLock:
print("Sending - "+self.roomNo+self.fileName+" "+self.hostUserName)
funcs.send_message(self.clientSock,self.hostUserNo,self.roomNo+self.fileName+" "+self.hostUserName,self.fileNo) # sent first signal
def __del__(self):
self.wait()
def run(self):
room = self.roomNo.encode("utf-8")
while True:
rd = self.f.read(funcs.CHUNK_SIZE)
data = room+rd
data = funcs.create_packet(self.hostUserNo,self.fileNo,data)
with sockLock:
funcs.send_data(self.clientSock,data)
if rd == b'':
break
self.f.close()
print("File "+self.fileName+" sent")
self.sendingCompleteSignal.emit(self.fileName)
class chatWin(QtWidgets.QWidget,Ui_chatBox):
def __init__(self,message,name,uno,room,sock,parent = None):
super(chatWin,self).__init__()
self.setupUi(self,message)
self.parent = parent
self.hostUserName = name
self.hostUserNo = uno
self.clientSock = sock
room = funcs.threeDigit(room)
self.room = room
self.fileNo = 1
self.fileList = {}
# connections
self.userChat.returnPressed.connect(self.handleSend)
self.listOnline.clicked.connect(self.handleOnline)
self.exitButton.clicked.connect(self.handleClose)
self.sendButton.clicked.connect(self.userChat.returnPressed)
self.fileSendButton.clicked.connect(self.handleFileSend)
def handleClose(self):
message = self.room + self.hostUserName+" left the room."
try:
with sockLock:
funcs.send_message(self.clientSock,self.hostUserNo,message)
self.close()
except ConnectionError:
self.chat.append("Server seems offline")
def handleSend(self):
message = self.userChat.toPlainText()
if not message:
return
self.userChat.clear()
self.updateChat(self.hostUserName+" : "+message)
message = self.room+self.hostUserName + " : " +message
try:
#print(message)
with sockLock:
print("Sending ",message)
funcs.send_message(self.clientSock,self.hostUserNo,message)
except ConnectionError:
self.chat.append("Server seems offline")
def updateChat(self,message):
self.chat.append(message)
def handleOnline(self):
self.parent.show()
def writeFile(self,key,data):
if not self.fileList.get(key): #newFile
msg = data.decode('utf-8')
self.fileList[key] = queue.Queue()
print("Newfile "+msg+" key "+key+" queue "+str(self.fileList[key]))
th = writingThread(msg,self.fileList[key],key,self)
th.completeSignal.connect(self.fileComplete)
th.start()
else:
self.fileList[key].put(data)
def fileComplete(self,key,fileName,senderName):
print("File Complete")
self.updateChat("File "+fileName+" recieved from "+senderName)
del self.fileList[key]
def handleFileSend(self):
fileName = self.userChat.toPlainText()
if not fileName:
return
print("Sending Filename = " + fileName)
self.updateChat("Sending Filename " + fileName)
msg = self.room+self.hostUserName+" is sending file "+fileName
try:
with sockLock:
funcs.send_message(self.clientSock,self.hostUserNo,msg)
th = readingThread(self.clientSock,self.hostUserNo,self.fileNo,self.room,self.hostUserName,fileName,self)
th.sendingCompleteSignal.connect(self.sendingComplete)
self.fileNo +=1
th.start()
except ConnectionError:
self.chat.append("Server seems offline")
def sendingComplete(self,name):
self.updateChat("File "+name+" sent")
class recievingThread(QtCore.QThread):
updateListSignal = QtCore.pyqtSignal(str)
newRoomSignal = QtCore.pyqtSignal(str,str)
routeMessageSignal = QtCore.pyqtSignal(str,str)
fileSignal = QtCore.pyqtSignal(str,str,bytes)
def __init__(self,sock,parent = None):
super(recievingThread,self).__init__()
self.parent = parent
self.clientSock =sock
def __del__(self):
self.wait()
def run(self): # Use Try except error handling
while True:
try:
uno , fno , size = funcs.recieve_header(self.clientSock)
if fno == 999:
msg = funcs.recieve_message(self.clientSock,size)
room = msg[0:3]
msg = msg[3:len(msg)]
print("Recieved ",msg)
self.routeMessageSignal.emit(room,msg)
elif fno == 998: # new room creation
msg = funcs.recieve_message(self.clientSock,size)
msg = msg.split(' ',1)
newroom = msg[0]
msg = msg[1]
self.newRoomSignal.emit(newroom,msg)
elif fno == 997: # update list
msg = funcs.recieve_message(self.clientSock,size)
self.updateListSignal.emit(msg)
elif fno <997:
uno = str(uno)
fno = str(fno)
key = uno+fno
data = funcs.recieve_data(self.clientSock,size)
room = data[0:3].decode('utf-8')
print("Recieved data for room "+room+" key = "+key)
data = data[3:]
self.fileSignal.emit(room,key,data)
except ConnectionError:
pass # to do error handling
class clWin(QtWidgets.QMainWindow,Ui_clientWin):
newFile = QtCore.pyqtSignal()
def __init__(self,parent = None):
super(clWin,self).__init__(parent)
self.setupUi(self)
self.rooms = {}
self.show()
self.clientSock = clientSock
self.hostUserNo = hostUserNo
self.hostUserName = hostUserName
self.hostMacAdress = hostMacAdress
# refresh timer to update list
self.refreshTimer = QtCore.QTimer(self)
self.refreshTimer.setInterval(10000)
#connections
self.refreshButton.clicked.connect(self.sendRefresh)
self.roomButton.clicked.connect(self.makeRoom)
self.exitButton.clicked.connect(self.close)
self.refreshTimer.timeout.connect(self.sendRefresh)
def makeRoom(self):
users = ''
items = self.onlineList.selectedItems()
for item in items:
users += item.text()+","
users = users[0:len(users)-1]
with sockLock:
funcs.send_connect(self.clientSock,self.hostUserNo,users)
def sendRefresh(self):
with sockLock:
funcs.send_message(self.clientSock,self.hostUserNo,'',997)
def startRecieve(self):
self.sendRefresh()
self.refreshTimer.start()
self.recvThread = recievingThread(self.clientSock,self)
self.recvThread.updateListSignal.connect(self.refreshList)
self.recvThread.newRoomSignal.connect(self.newRoom)
self.recvThread.routeMessageSignal.connect(self.routeMessage)
self.recvThread.fileSignal.connect(self.handleFile)
self.recvThread.start()
def refreshList(self,msg):
self.onlineList.clear()
msg = msg.split(" ")
for user in msg:
self.onlineList.addItem(user)
def newRoom(self,roomNo,tittle):
print("New Room "+roomNo)
self.rooms[roomNo] = chatWin(tittle,self.hostUserName,self.hostUserNo,roomNo,self.clientSock,self)
self.rooms[roomNo].show()
self.hide()
def routeMessage(self,roomNo,message):
print("Routing ",message)
self.rooms[roomNo].updateChat(message)
def handleFile(self,roomNo,key,data):
if data == b'':
self.rooms[roomNo].writeFile(key,None)
else:
self.rooms[roomNo].writeFile(key,data)
class RegWin(QtWidgets.QMainWindow,Ui_regWin):
def __init__(self,parent = None):
super(RegWin,self).__init__(parent)
self.setupUi(self)
self.connectionError = False
# Connections
self.exitButton.clicked.connect(self.close)
self.userName.returnPressed.connect(self.connectButton.animateClick)
self.connectButton.clicked.connect(self.handleConnect)
self.show()
try :
global clientSock
clientSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSock.connect((HOST,PORT))
except(ConnectionError):
self.serverStatus.setText("Server Offline: Cannot Connect, press Exit to Exit")
self.connectionError = True
def handleConnect(self):
if self.connectionError:
return
global hostUserName
name = self.userName.text()
self.userName.clear()
if(name):
print("UserNameEntered = ",name)
try:
funcs.send_message(clientSock,0,hostMacAdress+','+name)
uno , fno , size = funcs.recieve_header(clientSock)
reply = funcs.recieve_message(clientSock,size)
self.serverStatus.setText(reply)
print(reply)
if reply[0] == 'C':
uno , fno , size = funcs.recieve_header(clientSock)
hostUserName = name
hostUserNo = uno
QtCore.QTimer.singleShot(200,self.close)
except(ConnectionError):
self.appName.setText("Cannot Connect, press Exit to Exit")
self.connectionError = True
else:
self.serverStatus.setText("Enter a valid name")
if __name__ == "__main__":
hostMacAdress = funcs.getmac()
Regapp = QtWidgets.QApplication(sys.argv)
window = RegWin()
Regapp.exec_()
if not hostUserName:
exit()
clapp = QtWidgets.QApplication(sys.argv)
win = clWin()
win.startRecieve()
clapp.exec_()
#print(hostUserName)
print('Exiting')