class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): global lock print("new thread handling connection from", self.addr) while True: try: filename = self.fsock.receive(debug) print("checking server for : ", filename.decode()) lock.acquire() sentfile = filename.decode() sentfile = "receive_" + sentfile print(sentfile) if exists(sentfile): self.fsock.send(b"True", debug) lock.release() else: self.fsock.send(b"False", debug) payload = self.fsock.receive(debug) outfile = open(sentfile, "wb") outfile.write(filename) outfile.write(payload) self.fsock.send(b"wrote new file", debug) lock.release() outfile.close() except: print("Connection to the client lost.") sys.exit(0)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) serverFile = self.fsock.receive(debug) fileLock.acquire() fileTransfer(serverFile) fileLock.release() nfile = serverFile.decode() nfile = "transfered"+nfile if exists(nfile): self.fsock.send(b"True",debug) else: self.fsock.send(b"False", debug) payload = self.fsock.receive(debug) if debug: print("rec'd: ",payload) if not payload: if debug: print(f"thread connected to {addr} done") self.fsock.close() return outfile = open(nfile,"wb") outfile.write(serverFile) outfile.write(payload) fileDisconnect(serverFile) ## Thread done with file self.fsock.send(b"file saved to server",debug)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) filename = self.fsock.receive(debug) ## GET FILENAME ## ACQUIRE filelock.acquire() FileTransferStart( filename) ## Check if thread is using filename already filelock.release() newfile = filename.decode() newfile = "new" + newfile if exists(newfile): self.fsock.send(b"True", debug) else: self.fsock.send(b"False", debug) payload = self.fsock.receive(debug) if debug: print("rec'd: ", payload) if not payload: if debug: print(f"thread connected to {addr} done") self.fsock.close() return outfile = open(newfile, "wb") outfile.write(filename) outfile.write(payload) FileTransferEnd(filename) ## Thread done with file self.fsock.send(b"file saved to server", debug)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): #here our receiving takes place, ask for the name youd like for the file #place received data into the given file name print("new thread handling connection from", self.addr) lock.acquire() try: name = input("What would you like to name the file?" ) #self.fsock.receiveName(debug) if path.exists(name): print("That file already exists..!") sys.exit(1) #if the file already is being transferred if name in fileSet: print("That file is already being transferred!") lock.release() sys.exit(1) lock.release() lock.acquire() fileSet.add(name) self.fsock.receive(name, debug) print("done receiving..!") lock.release() fileSet.remove(name) finally: print("Transfer complete")
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("Thread connection from", self.addr) filename = self.fsock.receive(debug) lock.aquire() fileStart(filename) lock.release() file = filename.decode() file = "new" + flle if exists(file): self.fsock.send(b"True", debug) else: self.fsock.send(b"False", debug) payload = self.fsock.receive(debug) if debug: print("rec'd; : ", payload) if not payload: if debug: print(f"thread connected to {addr} ") self.fsock.close() return outputFile = open(file, "wb") outputFile.write(filename) outputFile.write(payload) fileEnd(filename) self.fsock.send(b" Thread done", debug)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) fileInfo = (self.fsock.receive(debug)).decode() print("The file's name, size and remote name file was received") print("File Info: ", fileInfo) fileName, fileSize, remoteFileName = fileInfo.split(":") fileSize = int(fileSize) #checks to see if file already exist path = os.getcwd()+"/"+remoteFileName if os.path.exists(path) is True: print("The file is already on the server") payload = self.fsock.receive(debug) self.fsock.send(payload, debug) else: with open (remoteFileName, "w") as f: print("File data is being recieved...") payload = self.fsock.receive(debug) #Decodes payload if it is not none and writes to the remote file #If payload is nothing is none then it writes nothing to the remote file if payload is not None: payloadDecoded = payload.decode() f.write(payloadDecoded) self.fsock.send(payload, debug) print("Exiting.....")
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) fileName = (self.fsock.receive(debug)).decode() print( "File name was recieved so it can check to see if it's currently being written to" ) print("Thread ", threading.current_thread(), "is waiting for a lock") lock.acquire() print("Thread ", threading.current_thread(), "lock was acquired") if fileTransferStart(fileName) is True: print("File is currently being transferred-Try Again") lock.release() sys.exit(0) else: print("File is not currently being transferred") pass fileInfo = (self.fsock.receive(debug)).decode() print("The file's name, size and remote name file was received") print("File Info: ", fileInfo) fileName, fileSize, remoteFileName = fileInfo.split(":") fileSize = int(fileSize) print( "File is being check to see if it is currently being transferred..." ) #checks to see if file already exist path = os.getcwd() + "/" + remoteFileName if os.path.exists(path) is True: print("The file is already on the server") payload = self.fsock.receive(debug) self.fsock.send(payload, debug) else: with open(remoteFileName, "w") as f: print("File data is being recieved...") payload = self.fsock.receive(debug) #Decodes payload if it is not none and writes to the remote file #If payload is nothing is none then it writes nothing to the remote file if payload is not None: payloadDecoded = payload.decode() f.write(payloadDecoded) self.fsock.send(payload, debug) lock.release() print("Thread ", threading.current_thread(), "lock was released") fileTransferEnd(fileName) print("Exiting.....")
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): while True: file = (self.fsock.receive(debug)).decode() fileName, fileSize = file.split(":") fileSize = int(fileSize) if (fileSize == 0): print("You entered an empty file") sys.exit(1) if (os.path.isfile(fileName)): print("file already exists") sys.exit(1) lock = threading.Lock() with lock: with open(fileName, "w+b") as newFile: count = 0 while count < fileSize: payload = self.fsock.receive(debug) data = bytes(payload) if payload == b'': break newFile.write(data) count += 1 newFile.close() if debug: print("rec'd: ", payload) if payload == b'': print("The file was received") sys.exit(0)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): global dictionary, dictLock print("new thread handling connection from", self.addr) payload = self.fsock.receive(debug) #receive file name to be saved if debug: print("rec'd: ", payload) if not payload: # done if debug: print(f"thread connected to {addr} done") self.fsock.close() #possible error return # exit payload = payload.decode( ) #receive byte array of name to be saved and convert to string if exists(payload): self.fsock.send(b"True", debug) else: dictLock.acquire( ) #Acquire lock to check if the wanted file is not already being saved by another thread currentCheck = dictionary.get(payload) if currentCheck == 'running': #Checking dictionary self.fsock.send(b"True", debug) dictLock.release() print("the file " + payload + " is currently being transfered") else: dictionary[ payload] = "running" #If it is not currently being transferred then the thread can transfer it and dictLock.release( ) #you write to the dictionary that you are transferring the file sleep(40) self.fsock.send( b"False", debug ) #Tell client that the file is not being transferred and does not exist in the try: #directory payload2 = self.fsock.receive(debug) #Receiving file data except: print("connection lost while receiving.") sys.exit(0) if not payload2: sys.exit(0) try: self.fsock.send(payload2, debug) except: print("------------------------------") print("connection lost while sending.") print("------------------------------") output = open(payload, 'wb') #open and set to write byte array output.write(payload2) #writing to file output.close() dictLock.acquire( ) #After the file has been written, delete it from the dictionary del dictionary[payload] dictLock.release() self.fsock.close()
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print('Connected by', self.addr) file_info = self.fsock.receive(debug).decode("utf-8").split(":") #First receives filename and file size from client. filename, file_size_str = file_info[0], file_info[1] print("File receiving: '" + filename + "' Size: " + file_size_str) file_size = int(file_size_str) if os.path.exists("received_files/" + filename) == True: #Checks if filename is in the directory self.fsock.send(b'1', debug) #Sends back to client that file exists on server directory print("File exists. Overwriting original...") else: self.fsock.send(b'0', debug) #Sends back to client that file does not exist on server directory lock.acquire() #Gets lock to check active files if filename in active_files: #If filename is in the list, then it will exit out. print("Cannot complete transfer. File is active.") self.fsock.close() lock.release() return else: #Adds file name to active list active_files.append(filename) lock.release() #Releases lock to resume normal function with open("received_files/" + filename, 'wb') as file: #Creates file to write data to while 1: data = self.fsock.receive(debug) #Receives data from client if debug: #Debug info print("Data received: ", data) if not data: #Exits if data is None type, non-existent, or end of file if file_size == os.path.getsize("received_files/" + filename): print("File: '" + filename + "' received!") else: print("File is incomplete due to a dropped connection. Transfer incomplete!") lock.acquire() active_files.remove(filename) #Removes active file(name) from list within lock lock.release() if debug: print(f"thread connected to {addr} done") self.fsock.close() #Close connection file.close() return file.write(data) #Writes to file self.fsock.send(data, debug) #Sends response back to client
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) filename = (self.fsock.receive(debug)).decode() print("\nFile is being checked for transfer status") if fileTransferStart(filename) is True: msg = "Waiting" msg = msg.encode() self.fsock.send(msg, debug) print("\nFile is currently being transferred - Please Wait") lock.aquire() msg = "ready for Transfer" msg = msg.encode() self.fsock.send(msg, debug) filesBeingTransferred.append(filename) print("\nThread", threading.current_thread(), "lock was acquired") else: msg = "Ready for transfer" msg = msg.encode() self.fsock.send(msg, debug) print("\nFile is not currently being transferred") lock.acquire() print("\nThread ", threading.current_thread(), "lock was acquired") serverfilename = (self.fsock.receive(debug)).decode() print("\nThe server file's name was received") #checks if the file already exit on server path = os.getcwd() + "/" + serverfilename if os.path.exits(path) is True: print("\nThe file is already on the server") payload = self.fsock.receive(debug) self.fsock.send(payload, debug) else: with open(serverfilename, "w") as f: print("\nFile data is being recieved...") payload = self.fsock.receive(debug) #Decodes payload if it is not none and writes to the remote file #If payload is nothing is none then it writes nothing to the remote file if payload is not None: payloadDecoded = payload.decode() f.write(payloadDecoded) self.fsock.send(payload, debug) lsock.release() print("\nThread ", threading.current_thread(), "lock was released") fileTransferEnd(filename) print("\nExisting......")
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) while True: fileName = self.fsock.receive() start = self.transferStart(fileName) if start: try: newFile = open(fileName,"x") except : print("File already exists!") self.fsock.send(b'File already exists on server, file not transfered') sys.exit(1) received = self.fsock.receive() if(received is None): os.remove(fileName) print("Something went wrong, the file could not be fully recieved") sys.exit(1) while received != b'DoneSendingFileFromClient': newFile.write(received.decode()) received = self.fsock.receive() if(received is None): os.remove(fileName) print("Something went wrong, the file could not be fully recieved") sys.exit(1) newFile.close() self.transferEnd(fileName) print("Finished receiving") self.fsock.send(b'Transfer Successful') else: self.fsock.send(b'Could not transfer file, try again later') return # exit def transferStart(self, fileName): fileLock.acquire() if fileName in activeFiles: fileLock.release() return False else: activeFiles[fileName] = fileName fileLock.release() return True def transferEnd(self, fileName): fileLock.acquire() activeFiles.pop(fileName) fileLock.release()
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) while True: lock.acquire() ### from framedSock import framedSend, framedReceive ################################################# fileName = self.fsock.receive(debug).decode() print("filename is ", fileName) conf = "filename received and stored" #framedSend(sock, conf.encode(), debug) self.fsock.send(conf.encode(), debug) path = os.getcwd() #/ filesPath = path + '/' + fileName print(filesPath) if (os.path.isfile(filesPath)): print("file already exists in server....exiting") #framedSend(sock, b"file exists", debug) self.fsock.send(b"file exists", debug) sys.exit(0) self.fsock.send(b"pass", debug) f = open(fileName, "w") ################################################ print("starting to write file....") while True: payload = self.fsock.receive(debug).decode() if debug: print("rec'd: ", payload) if payload == "end of file": closing = "end of file reached!" #framedSend(sock, closing.encode(), debug) self.fsock.send(closing.encode(), debug) f.close() lock.release() self.fsock.close() break f.write(payload) if not payload: self.fsock.close() return payload += "!" # make emphatic! self.fsock.send(payload.encode(), debug) break #for child
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): # time.sleep(4) print("\nNew thread handling connection from", self.addr) # lock the critical section for threads lock.acquire() # get file sent by client payload = self.fsock.receive(debug) if debug: print("rec'd: ", payload) # if nothing is sent, release the lock if not payload: print("Client tried to send an empty file or an unexistent file") # close the socket self.fsock.close() lock.release() sys.exit(1) name = payload.decode() try: # if it doesnt exist in server, create the file and write its contents to it if not os.path.isfile(name): # create a file and write the content of the sent file to it content = self.fsock.receive(debug) file = open(name, 'wb+') file.write(content) file.close() print("Received file", name) # send info back to the client self.fsock.send(b"File has been received by the server", debug) else: print("The File with name", name, "already exists on server.") # send info back to the client self.fsock.send(b"File already exists on th server", debug) except FileNotFoundError: print("File wasnt found") lock.release() self.fsock.close()
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("New thread handling connection from ", self.addr) while True: lock.acquire() start = self.fsock.receive(debug) try: start = start.decode() except AttributeError: print("error exiting: ", start) sys.exit(0) count = 0 for char in start: if char.isalpha(): break else: count = count + 1 start = start[count:] #where the file name ends start = start.split("\'start\'") #opening file file = open(start[0].strip(), "wb+") #recieving input while file has not ended while True: #error handling try: payload = self.fsock.receive(debug) except: pass if debug: print("received: ", payload) if not payload: break if b"\'end\'" in payload: file.close() lock.release() sys.exit(0) else: file.write(payload[1:])
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) while True: payload = self.fsock.receive(debug) if debug: print("rec'd: ", payload) if not payload: #connection done if debug: print(f"thread connected to %s done" % self.addr) self.fsock.close() return payload = payload.decode() lock.acquire() if debug: time.sleep(5) if exists(payload): self.fsock.send(b"True", debug) else: self.fsock.send(b"False", debug) try: payload2 = self.fsock.receive(debug) except: print("connection lost while receiving") sys.exit(0) if not payload2: break payload2 += b"!" try: self.fsock.send(payload2, debug) except: print("connection lost while sending") output = open(payload, 'wb') output.write(payload2) output.close() self.fsock.close() lock.release()
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.s, self.addr = sockAddr self.fs = EncapFramedSock(sockAddr) def run(self): print("New thread handling connection from", self.addr) while True: payload = "" try: filename, data = self.fs.receive(debug) except: print("Could not transfer file") sys.exit(1) if debug: print("Received: ", payload) if payload is None: print("The contents in this file were empty!") sys.exit(1) filename = filename.decode() if os.path.isfile(filename): print("This file already exists on the server.") sys.exit(1) else: lock_file_start(filename) writing = open(filename, 'w+b') writing.write(data) print("Data has been sent successfully!") writing.close() lock_file_end(filename) sys.exit(0)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.clientSock, self.cliendAddr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.cliendAddr) while True: payload = "" try: fileName, fileContents = self.fsock.receive(debug) except Exception as e: print("File transfer failed") print(e) sys.exit(0) conn, addr = s.accept() if debug: print("recieved: ", payload) if payload is None: print("File contents were empty, exiting...") sys.exit(0) fileName = fileName.decode() try: if not os.path.isfile("./received/" + fileName): #Get a lock to transfer the file lock.acquire() #If file is in current files then you can't write to it if fileName in current_files: print("File is currently being written to") lock.release() sys.exit(0) else: #If the file is not being written to then we can add it to the current files current_files.add(fileName) lock.release() currpath = os.path.dirname(os.path.realpath(__file__)) file = open(currpath + "/received/" + fileName, 'w+b') file.write(fileContents) file.close() print("File ", fileName, " recieved!") #get lock to make sure that current files is not being written to lock.acquire() #because file is no longer in use, remove from set current_files.remove(fileName) lock.release() sys.exit(0) else: print("File is already on the server") sys.exit(1) except FileNotFoundError as e: print("File was not found") print(e) sys.exit(0)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) numFiles = 0 while True: #recieve the name of the file fileFromClient = self.fsock.receive() fileNameFromC = fileFromClient.decode() #check if the file is in the list of files being used at the moment #if not append it so we know what files are being used and are locked if(fileNameFromC not in fileLockList): fileLockList.append(fileNameFromC) print("LOCKING FILE: "+fileNameFromC) print(*fileLockList) locker.acquire() #####lock this critical area for threads that dont have a lock so they cannot access this part payload = self.fsock.receive() #client sent the name of the file first so we got that #we can use the name to lock the file descriptor while its being used #we can put the name of the file on a dictionary/list/array object and if other threads #want to write to that same file they check if it is on the stack #if it is they have to wait for the lock #if not the we give the lock to the thread that wants to #write to that file on the server with that name #and when the thread is done remove the file name from the file dictionary/list/array object print("got file: " + fileFromClient.decode()) print("contents of file: " + payload.decode()) #write to new file on server #check if file exists #this will influence the file name by placing a number next to it fileNew = str(numFiles)+fileFromClient.decode() serverFile = open(fileNew, 'wb') serverFile.write(payload) serverFile.close() #done with this file close it and pop it from the list so it can be used again #our own method fileLockList.remove(fileNameFromC) locker.release() print("UNLOCKING FILE: "+fileNameFromC) print(*fileLockList)
class Server(Thread): def __init__(self, sockAddress): Thread.__init__(self) self.sock, self.address = sockAddress self.fsock = EncapFramedSock(sockAddress) def run(self): print("new thread handling connection from", self.address) while True: try: fileName, contents = self.fsock.receive(debug) except: print("Error: File transfer was not successful!") self.fsock.sendStatus(0, debug) self.fsock.close() sys.exit(1) if debug: print("Received", contents) # Data not received. Exit system. if fileName is None or contents is None: print("Client ", self.address, " has disconnected") sys.exit(0) lock.acquire() if debug: time.sleep(5) fileName = fileName.decode() self.writeFile(fileName, contents) self.fsock.sendStatus(1, debug) lock.release() def writeFile(self, fileName, contents): if fileName is None: raise TypeError if contents is None: raise TypeError try: # Check if there is a directory to receive files. if not os.path.exists(PATH): os.makedirs(PATH) os.chdir(PATH) # New file to open. writer = open(fileName, 'w+b') writer.write(contents) writer.close() print("File %s received from %s" % (fileName, self.address) ) # Prints output to ensure the file was received. except FileNotFoundError: print("File Not Found Error: File %s not found" % fileName) # File not found error. Exit. self.fsock.Status(0, debug) sys.exit(1)
class Server(Thread): def __init__(self, sockAddress): Thread.__init__(self) self.sock, self.address = sockAddress self.fsock = EncapFramedSock(sockAddress) def run(self): print("new thread handling connection from", self.address) while 1: try: print("try statement 1 ********") fileName, contents = self.fsock.receive() print("done **********") except: print("Error: File transfer was not successful!") self.fsock.sendStatus(0) self.fsock.close() sys.exit(1) # data not received if fileName is None or contents is None: print ("Client ", self.address, " has disconnected") sys.exit(0) print("writing *********") lock.acquire() # write the file fileName = fileName.decode() self.writeFile(fileName, contents) self.fsock.sendStatus(1) lock.release() print("release *********") def writeFile(self, fileName, contents): if fileName is None: raise TypeError if contents is None: raise TypeError try: # check if dir exists to receive files if not os.path.exists(PATH): os.makedirs(PATH) os.chdir(PATH) # create file to write writer = open(fileName, 'w+b') writer.write(contents) writer.close() print("File %s received from %s" % (fileName, self.address)) except FileNotFoundError: print("File Not Found Error: File %s not found" % fileName) self.fsock.Status(0) sys.exit(1)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) while True: payload = self.fsock.receive(debug) if debug: print("rec'd: ", payload) if not payload: # done if debug: print(f"thread connected to {addr} done") self.fsock.close() return # exit while 1: sock, addr = lsock.accept() print("Connection from", addr) while working: payloadFileName = framedReceive(sock, debug) if not payloadFileName: working = False break lock.aquire() payloadFileName = payloadFileName.decode() if exists(payloadFileName): framedSend(sock, b"True",1) else: framedSend(sock, b"False",1) try: payloadTxt = framedReceive(sock, debug) except: print("Connection with ",addr ,"lost ") sys.exit(0) lock.release() try: framedSend(sock,b"Message Completed!",debug) except: print("Connection with ",addr ,"lost ") sys.exit(0) lock.release() output = open(payloadFileName, 'a') payloadTxt = payloadTxt.decode() output.write(payloadTxt) output.close() lock.release()
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): global dictionary, dictLock print("new thread handling connection from", self.addr) while True: payload = self.fsock.receive() if not payload: self.fsock.close() return payload = payload.decode() if exists(payload): self.fsock.send(b"True") else: dictLock.acquire() currentCheck = dictionary.get(payload) if currentCheck == 'running': self.fsock.send(b"True") dictLock.release() else: dictionary[payload] = "running" dictLock.release() self.fsock.send(b"False") payload2 = self.fsock.receive() if not payload2: sys.exit(0) self.fsock.send(payload2) output = open(payload, 'wb') output.write(payload2) output.close() dictLock.acquire() del dictionary[payload] dictLock.release() self.fsock.close()
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) while True: lock.acquire() filename = self.fsock.receive(debug) if debug: print("rec'd: ", filename) if filename is None: # done if debug: print("thread connected to {addr} done") #removed f here self.fsock.close() lock.release() return filename = filename.decode() if filename in files_being_transfered: self.fsock.send("True", debug) #remove b else: self.fsock.send("False", debug) #remove b files_being_transfered.append(filename) try: data = self.fsock.receive(debug) except: print( "Unable to receive and finalize transfer... terminating transfer..." ) sys.exit(0) open_file = open(filename, 'wb') open_file.write(data) open_file.close() self.sock.shutdown(socket.SHUT_RD) self.sock.close() lock.release()
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def writeFile(self, fName): filesInUse.update( {fName:'True'} ) #mark as now in use, do not touch while in use lock.acquire() with open(fName, 'rb') as fContext: readData = fContext.read() with open(DIR+fName, 'wb') as wFile: wFile.write(readData) lock.release() filesInUse.update( {fName:'False'} ) #make open for use def run(self): print("new thread handling connection from", self.addr) while True: #Recieve payload = self.fsock.receive(debug) if debug: print(f"thread connected to ((addr var goes here!))done") if not payload: # done self.fsock.close() return # exit #Decode and echo status = payload payload = payload.decode() #exit if 'exit' in payload: sys.exit(0) #write payload if os.path.exists(payload): #Check to see if in use if filesInUse.get(payload) == None or filesInUse.get(payload) == 'False': #pass in the file name self.writeFile(payload) #Sent self.fsock.send(b'DONE', debug) print('Done writing to: ', payload , '\n') else: self.fsock.send(b'File In use, try again', debug) else: self.fsock.send(b'File does not exist, try again', debug)
class Server(Thread): #create a class for threads for each incoming connection def __init__( self, sockAddr ): #takes the socket and address tuple returned from .accept() Thread.__init__(self) self.sock, self.addr = sockAddr #putting the tuple into seperate variables self.fsock = EncapFramedSock( sockAddr ) #create an object from EncapFramedSock to recieve an EncapFramedSock message from the client def run(self): print("new thread handling connection from", self.addr) while True: payload = "" try: fileName, fileContents = self.fsock.receive( debug ) #gets the filename and whats in the file from using the recieve method from EncapFramedSock except: print("File transfer failed") sys.exit(1) if debug: print("rec'd", payload) if payload is None: print("File contents were empty, exit...") sys.exit(1) fileName = fileName.decode() try: if not os.path.isfile("./RecievedFiles/" + fileName ): #if the file doesnt already exist file_transfer_start(fileName) file = open("./RecievedFiles/" + fileName, 'w+b') #opens a new file file.write(fileContents) #writes to the file file.close() #closes it print("File", fileName, "accepted") file_transfer_end(fileName) sys.exit(0) else: #if the file already exists it just exits print("File with name", fileName, "already exits, exit...") sys.exit(1) except FileNotFoundError: print("Fail") sys.exit(1)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) while True: payload = self.fsock.receive(debug) if debug: print("rec'd: ", payload) if not payload: # done if debug: print(f"thread connected to {addr} done") self.fsock.close() return # exit payload += b"!" # make emphatic! self.fsock.send(payload, debug)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.threadSock = EncapFramedSock(sockAddr) def write_file(self, filename, data): try: # check if the dir exists else create it if not os.path.exists("./serverFiles/"): os.makedirs("./serverFiles/") # check if the file recieved is not on the server already if os.path.exists("./serverFiles/" + filename): print("File already exists on server. Not sent.") return lock.acquire() # create the file and write to it. file_writer = open("./serverFiles/" + filename, 'w+b') file_writer.write(data) print("Writing to file...") lock.release() # close file file_writer.close() print("file %s was recieved from address %s" %(filename, self.addr)) except FileNotFoundError: print("ERROR: file %s not found " % filename) sys.exit(1) def run(self): print("new thread handling connection from", self.addr) while True: filename, data = self.threadSock.receive() # if data was not received close client if filename is None or data is None: print("client ", self.addr, " disconnected") sys.exit(0) # write to file and save it filename = filename.decode() print(self.addr, " will attempt to save file %s" % filename) self.write_file(filename, data)
class Server(Thread): def __init__(self, sockAddr): Thread.__init__(self) self.sock, self.addr = sockAddr self.fsock = EncapFramedSock(sockAddr) def run(self): print("new thread handling connection from", self.addr) global lock, currentFile # need to use global keyword because of threads while True: try: payload = self.fsock.receive(debug) if payload == b'': # means we've reached end lock.acquire() # Locks is needed in case two threads try to access the dict at the same time de = "" for i in currentFile: # This is needed since we don't know the name of the file if currentFile[i] == self.addr[1]: de = i currentFile.pop(de) lock.release() break if payload != None: f, data = re.split(':', payload.decode()) if len(currentFile) > 0 and f in currentFile and currentFile[f] != self.addr[1]: print('Failed to send file, file is in use') self.fsock.send(b'abort', debug) # letting client know someone is using the file sys.exit(1) else: if len(currentFile) == 0 or not f in currentFile: fd = open(f, 'w+') # if first time writing to file then create new file else: fd = open(f, 'a+') # otherwise just append lock.acquire() currentFile[f] = self.addr[1] # using addr[1] as the differentiator lock.release() fd.write(data) fd.close() if debug: print("rec'd", payload.decode()) self.fsock.send('Successfuly received and wrote line'.encode(), debug) except Exception as e: print('Exception: Could not finish receiving file\n', e) sys.exit(1) self.fsock.send('Successfuly received file'.encode(), debug)
def main(): arguments = parseArguments() addrFamily = socket.AF_INET socktype = socket.SOCK_STREAM addrPort = (arguments["host"], arguments["port"]) clientSocket = socket.socket(addrFamily, socktype) if clientSocket is None: print('could not open socket') sys.exit(1) clientSocket.connect(addrPort) fsock = EncapFramedSock((clientSocket, addrPort)) sendFile(fsock, arguments["source"], arguments["destination"]) transferResult = fsock.receive() transferResult = transferResult.decode() print(transferResult)