def run(self): s = None for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(" error: %s" % msg) s = None continue try: print(" attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(" error: %s" % msg) s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) fs = FramedStreamSock(s, debug=debug) text = readFile() fs.sendmsg(text.encode()) print("Recived: " + fs.receivemsg().decode("utf-8"))
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): lock.acquire() while True: # print("new thread.....") msg = self.fsock.receivemsg() if msg: writeToFile(msg, self) if not msg: if self.debug: print(self.fsock, "server thread done") lock.release() return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode() print(msg) self.fsock.sendmsg(msg) lock.release() #Stops the thread in case of existing file def stop(self): self.running = False
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): while True: msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 inputFile = msg.decode() fileExist = os.path.isfile("uploadServer/" + inputFile) self.fsock.sendmsg(b"Ready") openedFile = open('uploadServer/' + inputFile, "w") data = self.fsock.receivemsg() while(data.decode() != "exit"): #print("Reading: " + data.decode()) openedFile.write(data.decode()) data = self.fsock.receivemsg() openedFile.close() print("Recieved:", inputFile)
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=False) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): while True: print("Starting thread") print("trying to receive") msg = self.fsock.receivemsg() fileName = "" fileText = "" state = "get filename" while msg: msg = msg.decode() print(msg) if (state == "get filename"): fileName = msg state = "get msg" elif (state == "get msg"): fileText += msg msg = self.fsock.receivemsg() # Write to file oF = open(fileName, "w+") for line in fileText: oF.write(line) oF.close print("Done transfering") return
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): msg = self.fsock.receivemsg() msg = msg.decode('ascii') fileopen = open("serverFiles/" + msg, 'w') while True: msg = self.fsock.receivemsg() msg = msg.decode('ascii') print("Recieved: ", msg) fileopen.write(msg) if not msg: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode()
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): lock.acquire() while True: header = self.fsock.receivemsg() if not header: lock.release() if self.debug: print(self.fsock, "server thread done") return fileName = header.decode() payload = self.fsock.receivemsg() path = (newPath + '/' + fileName) out_file = open(path, "wb+") #[w]rite as [b]inary out_file.write(payload) out_file.close() requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 print("Done! %s" % requestNum) lock.release()
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): lock.acquire() file_name = True while True: try: if file_name: name = str(self.fsock.receivemsg())[2:-1] fl = open('server ' + name, 'wb+') file_name = False else: msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") fl.close() return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode() self.fsock.sendmsg(msg) except: fl.close() lock.release() fl.close() lock.release()
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): print("new thread handling connection from", addr) try: with open('FileRequest'+str(ServerThread.requestCount)+'.txt', "wb") as f: while True: msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount # time.sleep(0.001) ServerThread.requestCount = requestNum + 1 lock.acquire() f.write(msg+bytes('\n','utf-8')) lock.release() msg = ("%s! (%d)" % (msg, requestNum)).encode() self.fsock.sendmsg(msg) f.close() finally:
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): fileNameRead = False lock.acquire() f = open('server_default', 'w') f.close() while True: try: if fileNameRead: f.write(self.fsock.receivemsg()) if not self.fsock.receivemsg(): if self.debug: print(self.fsock, "server thread done") f.close() return requestNum = ServerThread.requestCount ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode() self.fsock.sendmsg(msg) else: fileName = str(self.fsock.receivemsg()) fileName = 'serverTransfered_' + fileName f = open(fileName, 'wb+') except: lock.release() f.close() print('Race condition prevented') pass
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): try: msg = self.fsock.receivemsg() msg = msg.decode() Lock.acquire() # makes sure only one thread is running oFile = open(msg,"wb+") while True: msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") return if b'%%e' in msg: oFile.close() Lock.release() return oFile.write(msg) self.fsock.sendmsg(msg) except (TypeError) : sys.exit(1)
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): lock.acquire() # lock execution until release while True: header = self.fsock.receivemsg() if not header: lock.release() if self.debug: print(self.fsock, "server thread done") return fileName = header.decode() # convert to string by decoding bytes payload = self.fsock.receivemsg() wrtieFile = open(os.getcwd() + "/serverFiles/" + fileName, 'wb') wrtieFile.write(payload) wrtieFile.close() # write the new file and close it requestNum = ServerThread.requestCount ServerThread.requestCount = requestNum + 1 print("complete %s" % (requestNum + 1)) # prints number of file transfers lock.release() # unlocked and returns
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): while True: msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount #time.sleep(0.001) ServerThread.requestCount = requestNum + 1 #lock.acquire(True, -1) file_n = msg if b".txt" in file_n: # create/open file f = open(file_n, "wb") print("Text file: " + file_n.decode()) file = msg f.write(file) print("Writing..." + file.decode()) file = ("%s! (%d)" % (file, requestNum)).encode() self.fsock.sendmsg(file)
class ServerThread(Thread): requestCount = 0 def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): mutex.acquire() name = self.fsock.receivemsg() name = name.decode() name = name[:-4] name = name + "-server.txt" if os.path.isfile(name): name = name[:-4] name = name + "(1).txt" count = 2 while os.path.isfile(name): name = name[:-7] name = name + "(" + str(count) + ").txt" count += 1 aFile = open(name, "w") while True: line = self.fsock.receivemsg() line = line + b'\n' line = line.decode() aFile.write(line) if debug: print("rec'd: ", line) if not line: if debug: print("child exiting") break aFile.close() mutex.release()
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): while True: msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode() self.fsock.sendmsg(msg) cnt = 0 while True: sock, addr = lsock.accept() ServerThread(sock, debug) print('Connected by', addr) while True: data = fs.receivemsg() dataRcv = data.decode() if not data: break print(dataRcv) s.sendmsg(s, b':' + data, debug) sock.close()
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): if not "Server" in os.getcwd(): os.chdir("Server") start = self.fsock.receivemsg() try: start = start.decode() except AttributeError: print("error exiting: ", start) return count = 0 for char in start: if char.isalpha(): break else: count = count + 1 start = start[count:] #tells server where file name ends start = start.split("\'start\'") #opening file file = open((start[0]).strip(), "wb+") #lock the server requestNum = ServerThread.requestCount ServerThread.requestCount = requestNum + 1 if lock: lock.acquire(True) print("Thread is now locked for input", requestNum) #Receives input while file has not ended while True: #error handling try: payload = self.fsock.receivemsg() except: pass #checking for debugging if debug: print("rec'd: ", payload) if not payload: break #checking if end of file else writes to file if b"\'end\'" in payload: lock.release() print("releasing lock for other threads") file.close() return else: file.write(payload)
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): # Locking the code for one thread at a time lock.acquire(1) # Getting current directory, to create subdirectory for server files cwd = os.getcwd() # Creating variable for filename from server fileName = '' while fileName == '': # Recieve first payload and grab filename headerPayload = self.fsock.receivemsg() if headerPayload: pl = headerPayload.decode().split() if b'start' in headerPayload: fileName = pl[-1] # Creating subdirectory if it does not exist if not os.path.exists(cwd + '/serverDirectory/'): os.makedirs(cwd + '/serverDirectory') # Creating file if it does not exist fileOpen = open( os.path.join(cwd + '/serverDirectory/', fileName), 'wb+') fileOpen.close() break while True: payload = self.fsock.receivemsg() if not payload: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 # Replacing newline characters payload = payload.decode().replace('~`', '\n') if debug: print("rec'd: ", payload) # Opening file to write to fileOpen = open(cwd + '/serverDirectory/%s' % fileName, 'a') try: # If the file ending symbol is sent, close and send success message if '~fInIs' in payload: fileOpen.close() # Releasing thread because file is done being sent lock.release() return else: fileOpen.write(payload) except FileNotFoundError: print("Error trying to receive file")
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.lock = threading.Lock() # Here's our lock! self.start() def run(self): msg = self.fsock.receivemsg() # First receive checks for error. if (msg == b"error"): # If you get an error message, stop! print("Something went wrong client-side. Stopping...") self.fsock.sock.close() return msg = self.fsock.receivemsg() # Second receive checks for file name! while ( msg != b"" ): # Recieve filename and stop when client sends an empty array. fileName = msg.decode("utf-8") msg = self.fsock.receivemsg() filePath = os.getcwd() + "/server/" + fileName #Build path for file. if debug: print(self.fsock, "Waiting for lock.") self.lock.acquire( ) # We want whatever thread gets here first to claim the file. if debug: print(self.fsock, "Lock acquired.") if os.path.isfile( filePath ): # Don't allow overwrite of an already-existing file. This is meant to handle race condition. print(self.fsock, ": file already exists! Stopping.") self.lock.release() # Let go of the lock if you're done! #self.fsock.sendmsg(b"exists") #Supposed to let client know the file exists already. Always "none" for some reason. if debug: print(self.fsock, "lock released.") self.fsock.sock.close() return myFile = open(filePath, 'wb') self.lock.release( ) # First one here has claimed the file name - let the other threads come through. if debug: print(self.fsock, "relased lock.") while True: # Write to file until there is nothing to recieve! msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") myFile.close() print(self.fsock, ": %s recieved." % fileName) self.fsock.sock.close() return myFile.write(msg)
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): from os import listdir #these three lines implement a method get all file names in a folder efficiently. I took this from: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory#3207973 from os.path import isfile, join fileDict = [f for f in listdir(strPath) if isfile(join(strPath, f))] #line three referenced above. nxtIsFile = False strFILEPATH = "" writeLine = False while True: # loop within the threads for the server. payload = self.fsock.receivemsg() payOrig = payload payload = payload.decode('utf-8') print("Payload :" + payload) if not payload: if self.debug: print(self.fsock, "server thread done") return if ( writeLine ): #these conditionals all work in reverse order. essentially bottom condition should run first then top should run last. if ( payload != "CLOSEFILE" ): #then we should write to the file. That will be the line we just received. with open(strFILEPATH, 'a') as createdFile: createdFile.write(payload + '\n') createdFile.close() else: writeLine = False if (nxtIsFile): fileGiven = open(strPath + "/" + payload, 'wb+') #open file in server area to write to. strFILEPATH = strPath + "/" + payload writeLine = True fileGiven.close() nxtIsFile = False if (payload == "OPENFILE"): nxtIsFile = True msg = ("%s (%s)" % ("Wrote", payOrig)).encode() #return to user what we saw. self.fsock.sendmsg(msg)
def run(self): s = None for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(" error: %s" % msg) s = None continue try: print(" attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(" error: %s" % msg) s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) fs = FramedStreamSock(s, debug=debug) txtFile = input("Enter filename: ") with open(txtFile, "rb") as txt: try: content = txt.read(100) print('file opened') while content: fs.sendmsg(self, b':' + content) data = txt.read(100) except (FileNotFoundError) as fnferror: print("File not found...") sys.exit(0) except BrokenPipeError as BPError: print("Connection lost... ") sys.exit(0) if not content: print("file is empty.") sys.exit(0) else: print("recieved: ", fs.receivemsg())
def run(self): s = None for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(" error: %s" % msg) s = None continue try: print(" attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(" error: %s" % msg) s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) try: # Try to open the file to put on server. file = open(file_name, 'r') # Open the file. if debug: print("OPENED FILE") data = file.read(100) # Read 100 bytes from the file. except IOError: print("File does not exists or unable to open. Shutting down!" ) # Shutdown if unable to open file. sys.exit(0) fs = FramedStreamSock(s, debug=debug) fs.sendmsg(file_name.encode()) # Send the file request. response = fs.receivemsg() # Wait for response. if response.decode( ) == "File exists": # If file already on the server shutdown. print("The file is already in the server. Closing the thread.") file.close() # Close the file. return else: # Finish sending the rest of the file 100 bytes at the time. print("Sending the file to the server!") while data: fs.sendmsg(data.encode() ) # Send the data in the file, 100 bytes at a time. data = file.read(100) # Read the next 100 bytes. file.close() # Close the file when done reading. fs.sendmsg( b"" ) # Send empty string to tell server client is done sending the file.
def processData(data, thread_safe): if thread_safe: mutex.acquire() try: thread_id = threading.get_ident() #print('\nProcessing data:', data, "ThreadId:", thread_id) fs = FramedStreamSock(s, debug=debug) SendDet = "Processing data: = " + str(data) fs.sendmsg(SendDet.encode('utf-8')) print("received:", fs.receivemsg()) #framedSend(s, SendDet.encode('utf-8') , debug) finally: if thread_safe: mutex.release()
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): fileODone = False fName = "" while True: msg = self.fsock.receivemsg() if msg: fileString = msg.decode().replace("\x00", "\n") if not fileODone: #To Create a New File if it's the first line received auxS = fileString.split("//myname") fName = auxS[0] if fName in myDict: #If file exist we should acquire the corresponding lock in the dictionary to wait for the colliding thread to end print("It's in Lock Dictionary: " + fName) myLock = myDict[fName] myLock.acquire() else: #If it doesn't we create the lock and acquire it print("It's not in Lock Dictionary: " + fName) myDict[fName] = Lock() myDict[fName].acquire() print("lock done") myPath = os.path.join(os.getcwd()+"/receiving/"+auxS[0]) myFile = open(myPath, "w+") myFile.write(auxS[1]) fileODone = True print("File Opened: " + fName) else: #If it's another line we just append it print("In Msg, fileODone true") myFile.write(fileString) msg = msg + b"!" requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode() self.fsock.sendmsg(msg) if not msg: #When we have stopped receiving messages print("File Ending: "+fName) myDict[fName].release() #Release Lock myDict.pop(fName) #Remove Key myFile.close() return
def run(self): s = None for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(" error: %s" % msg) s = None continue try: print(" attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(" error: %s" % msg) s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) fs = FramedStreamSock(s, debug=debug) send_message(fs, "put t.txt")
def run(self): s = None for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_INET, socket.SOCK_STREAM, 0, 0): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(msg) s = None continue try: print(" attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(msg) s.close() s = None continue break if s is None: print('could not open socket') lock.release() sys.exit(1) fs = FramedStreamSock(s, debug=debug) # critical section lock.acquire() print("\nput ", filename) put(fs, filename) print("Transfer complete\n") lock.release()
class ServerThread(Thread): request_count = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): while True: data = self.fsock.receive_file() if data: filename, contents = data if filename and contents: # file received successfully with lock: # try forcing a race condition request_num = ServerThread.request_count time.sleep(0.001) ServerThread.request_count = request_num + 1 with open(storage_dir + filename, 'wb') as file: file.write(contents) print('Request number:', request_num) print(' Downloaded file:', filename) continue else: print(' Filename or contents empty') else: print('Connection ended with', addr) exit()
class FileServerThread(Thread): _lock = Lock() def __init__(self, soc, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): while True: message = self.fsock.receivemsg() if not message: return cf_model = pickle.loads(message) ## wraps the file writes with a lock with self._lock: ## set the mode based on whether the client wants to appent or overwrite if cf_model.append: file_mode = 'at' else: file_mode = 'wt' with open(os.path.join(STORE, cf_model.file_name), file_mode) as f: f.write(cf_model.contents)
def run(self): s = None for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(" error: %s" % msg) s = None continue try: print(" attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(" error: %s" % msg) s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) fs = FramedStreamSock(s, debug=debug) inputStr = input("Input your file's name: ") #If file does not exist it will keep prompting the user to send the name of an existing file while not os.path.exists(inputStr): print("Invalid File, Try Again") inputStr = input("Input your file's name: ") inFile = open(inputStr, 'rb') #Try catch block to handle errors while reading the file try: #File's name is sent first to create file on server side print("sending name: " + inputStr) fs.sendmsg(bytes(inputStr.rstrip("\n\r"), encoding='ascii')) print("received:", fs.receivemsg()) #For every line in the file the client will send a message containing that line print("Sending...\n") l = inFile.read(100) while (l): print("sending: ") fs.sendmsg(l) print("received:", fs.receivemsg()) time.sleep(0.001) l = inFile.read(100) except Exception as e: print(e) print("Error reading file")
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): while True: msg = self.fsock.receivemsg() if not msg: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode() self.fsock.sendmsg(msg)
def run(self): s = None for res in socket.getaddrinfo(serverHost, serverPort, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: print("creating sock: af=%d, type=%d, proto=%d" % (af, socktype, proto)) s = socket.socket(af, socktype, proto) except socket.error as msg: print(" error: %s" % msg) s = None continue try: print(" attempting to connect to %s" % repr(sa)) s.connect(sa) except socket.error as msg: print(" error: %s" % msg) s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) fs = FramedStreamSock(s, debug=debug) print("sending FILE NAME") fs.sendmsg(fileName.encode()) r = fs.receivemsg() print("received:", r.decode()) if (r.decode() == "SUCCESS"): f = open(fileName, 'rb') line = f.read(100) while (line): #s.send(line) print("Client line: " + line.decode()) fs.sendmsg(line) time.sleep(0.001) #framedSend(s, line, debug) line = f.read(100) #framedSend(s, b"done", debug) fs.sendmsg(b"done") print("received:", fs.receivemsg().decode())
class ServerThread(Thread): requestCount = 0 # one instance / class def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): print("new thread handling connection from", addr) fileName = '' mssg = '' while True: # print('attempting to receive message') msg = self.fsock.receivemsg() # print('successfully received message') if not msg: print(self.fsock, "server thread done") break mssg += msg.decode('utf-8') if (not fileName): # Get file name fileName = mssg.split(" ", 1)[0] fileNameLen = len(fileName) mssg = mssg[fileNameLen + 1:] requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 msg = ("%s! (%d)" % (msg, requestNum)).encode() self.fsock.sendmsg(msg) # Creating file on the server with contents of message if os.path.isfile(fileName): print( "The file already exists on the server! Another file will not be created." ) else: if fileName: f = open(fileName, "w") f.write(mssg) f.close() else: print( 'The file you are trying to transfer is empty. Cancelling transfer. It might be due to being transferred already' )