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): 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("\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: 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): 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("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.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): 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("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('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) 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 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: if debug: print(f"thread connected to {addr} done") self.fsock.close() return # exit payload = payload.decode() transferStart(payload) output = open(payload, 'wb') output.write(payload) output.close() transferEnd(payload) self.fsock.send(payload, 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) 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 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): 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: 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.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)
if s is None: print('Could not open socket') sys.exit(1) s.connect(addrPort) fsock = EncapFramedSock((s, addrPort)) for _ in range(1): try: filename = input("Enter the file name: ") if exists(filename): file = open(filename, 'rb') payload = file.read() if len(payload) == 0: print("File is empty") sys.exit(0) else: fsock.send(filename.encode(), debug) # send filename to check for existance file_exists = fsock.receive(debug).decode() if file_exists == 'True': print("This file already exists") sys.exit(0) else: fsock.send(payload, debug) print("Server ", fsock.receive(debug).decode()) else: print("File '%s' doesn't exist." % filename) except: print("Connection to the server lost") sys.exit(0)
addrPort = (serverHost, serverPort) s = socket.socket(addrFamily, socktype) if s is None: print('could not open socket') sys.exit(1) s.connect(addrPort) fsock = EncapFramedSock((s, addrPort)) try: fileSize = os.path.getsize(fileName) if fileSize == 0: print("File size null") fileSize = str(fileSize) info = ((fileName + ":" + fileSize).encode()) fsock.send(info, debug) with open(fileName, "rb") as sentFile: for data in fileName: data = sentFile.read(1024) if data == "": break fsock.send(data, debug) print("File Sent") except FileNotFoundError: print("File was not found")
server, usage, debug = paramMap["server"], paramMap["usage"], paramMap["debug"] if usage: params.usage() try: print(server) HOST, PORT = re.split(":", server) PORT = int(PORT) except: print("Can't parse server:port from '%s'" % server) sys.exit(1) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: if s is None: print('could not open socket') sys.exit(1) try: s.connect((HOST, PORT)) encapSock = EncapFramedSock((s, (HOST, PORT))) file, filename = getFile() data = file.read() if len(data) == 0: print("Empty file.") sys.exit(1) print("sending file") encapSock.send(filename, data, debug) file.close() except ConnectionRefusedError: print("Could not connect to server!")
print(files) inputFile = input("Please select a file to send \n") #Attempt to read input as file try: with open(inputFile.strip(), "rb") as binaryFile: #read whole file as one data = binaryFile.read() if data == b'': print(inputFile + " is empty....Now Exiting") sys.exit(0) except FileNotFoundError: print("File not found....Now Exiting") sys.exit(0) try: #sends file info to server fsock.send(b':' + inputFile.strip().encode('utf-8') + b"\'start\'") except BrokenPipeError: print("Disconnected from server") sys.exit(0) while len(data) >= 100: line = data[:100] data = data[100:] try: fsock.send(b":" + line, debug) except BrokenPipeError: print("Disconected from server") sys.exit(0) if len(data) > 0: fsock.send(b":" + data, debug)
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(debug) #recieve 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( ) #recieve byte array and convert to string #self.fsock.send(payload, debug) if exists(payload): self.fsock.send(b"True", debug) else: print("1") dictLock.acquire() print('2') #payloadString = str(payload) currentCheck = dictionary.get(payload) print(dictionary) if currentCheck == 'running': self.fsock.send(b"True", debug) print('3') dictLock.release() print('4') print( "the file is currently being transfered, exiting now") else: print('5') dictionary[payload] = "running" dictLock.release() sleep(100) print('6') self.fsock.send(b"False", debug) #recieving file data try: payload2 = self.fsock.receive(debug) except: print("connection lost while recieving.") sys.exit(0) if not payload2: break payload2 += b"!" # make emphatic! 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 print('7') dictLock.acquire() del dictionary[payload] print('8') dictLock.release() print('9') output.close() self.fsock.close()
print("Can not parse server: port from '%s'" % server) sys.exit(1) addrFamily = socket.AF_INET #gets the address family(IPv4) socktype = socket.SOCK_STREAM #gets the type of scoket(TCP) addrPort = (serverHost, serverPort) s = socket.socket(addrFamily, socktype) #opens a socket if s is None: print("could not open socket") sys.exit(1) s.connect(addrPort) #establish a connection to the server encapSock = EncapFramedSock( (s, addrPort) ) #creat a EncapFramesSock object with the socket to use it to encapsulate the contents of the file to send to the server where it will recieve it fileContents = file.read() #get the file contents if len(fileContents) == 0: print("File is empty, exit...") sys.exit(1) print("sending filename") encapSock.send( fileName, fileContents, debug ) #send the encapsulated file contents to server along with the file name
addrFamily = socket.AF_INET socktype = socket.SOCK_STREAM addrPort = (serverHost, serverPort) sock = socket.socket(addrFamily, socktype) if sock is None: print('could not open socket') sys.exit(1) sock.connect(addrPort) fsock = EncapFramedSock((sock, addrPort)) while True: filename = input("File name: ") try: fileOpen = open(filename, "rb") break except FileNotFoundError: print("File not found") fileData = fileOpen.read() if len(fileData) == 0: print("File not sent, empty file") sys.exit(1) else: print("Sending file") fsock.send(fileData, debug)
print('could not open socket!') sys.exit(1) sock.connect(addrPort) fsock = EncapFramedSock((sock, addrPort)) for i in range(1): filename = input("Enter file name") if exists(filename): file = open(filename, 'rb') payload = file.read() if len(payload) ==0; print("Cant send empty file") sys.exit(0) else: fsock.send(filename.encode() , debug) fileExi = fsock.receive(debug).decode() if fileExi== 'True': print("File exists") sys.exit(0) elif fileExi == 'exists': print("There is another user on this server") sys.exit(0) else: fsock.send(payload,debug) print(" Server : ",fsock.receive(debug).decode()) else: print("File '%s' doesnt exist" % filename)
while True: filename = input("Enter file: ") filename.strip() # exit client if filename == "exit": sys.exit(0) else: if not filename: continue elif os.path.exists(filename): # open file and get data file = open(filename, "rb") data = file.read() if len(data) < 1: print("File %s, is empty" % filename) continue framedSocket.send(filename, data) print("Sending file...") # file does not exists else: print("ERROR: file %s not found. Try again" % filename) clientSocket.close()
"please write name of file you want to transfer to server(include extension i.e: .txt)" ) fileName = input() try: with open(fileName, 'r') as fl: allLines = fl.readlines() if len(allLines) == 0: print("file's empty....exiting") sys.exit(0) except FileNotFoundError: print("no such file or directory") sys.exit(1) ############################################ print("sending file name: '%s'" % fileName) fileName = "CreateAndDestroypt2.txt" fsock.send(fileName.encode(), debug) #data = s.recv(1024).decode() data = fsock.receive(debug) print("Received '%s'" % data) fExists = fsock.receive(debug) if fExists == b"file exists": print("file already exists...exiting") sys.exit(0) #f = open(fileName, "w") print("*************sending file contents!*****************") for i in allLines: i = i.encode() #framedSend(s,i,debug) fsock.send(i, debug)
fsock = EncapFramedSock((sock, addrPort)) file_to_send = input("type file to send : ") if exists(file_to_send): file_copy = open(file_to_send, 'rb') #open file file_data = file_copy.read() #save contents of file file_copy.close() if len(file_data) == 0: print("cannot send empty file") sys.exit(0) else: file_name = input("give us file name : ") #prompt for file name to be saved on server fsock.send(file_name.encode(), debug) #encode to convert to byte array file_exists = fsock.receive(debug) #server will return true or false file_exists = file_exists.decode() if file_exists == 'True': print("file already exists in server") sys.exit(0) else: try: fsock.send(file_data, debug) except: print("------------------------------") print("connection lost while sending.") print("------------------------------") sys.exit(0) try: fsock.receive(debug)