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 hello world") fs.sendmsg(b"hello world") print("received:", fs.receivemsg()) fs.sendmsg(b"hello world") print("received:", fs.receivemsg())
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=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() 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 #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 # 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): 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()
def processData(data, thread_safe, fileNameProvided): if thread_safe: mutex.acquire( ) #set this to prevent other threads from running in between these. try: thread_id = threading.get_ident() #print('\nProcessing data:', data, "ThreadId:", thread_id) fs = FramedStreamSock(s, debug=debug) #so we know that we have a file to process. fs.sendmsg("OPENFILE".encode( 'utf-8')) #tell server that the name of the file is coming next. print("received:", fs.receivemsg()) fs.sendmsg( fileNameProvided.encode('utf-8')) #send that file name next. print("received:", fs.receivemsg()) with open(fileNameProvided ) as f: #this loops through file writing each line. for line in f: #loop through all lines if they are small enough send else split in two and tack detail to end. val = line.strip() if (val.strip() == ""): fs.sendmsg("_____EMPTYLINE______".encode('utf-8')) else: fs.sendmsg(val.encode('utf-8')) print("received:", fs.receivemsg()) fs.sendmsg( "CLOSEFILE".encode('utf-8')) #tell server that the file is over. print("received:", fs.receivemsg()) finally: if thread_safe: mutex.release() #unlock for other threads to run.
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) 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) fs = FramedStreamSock(s, debug=debug) # while True: #message = input('>>>') message = 'put something.txt' split_message = message.split(' ') if split_message[0] == 'put': if os.path.isfile(split_message[1]): fs.sendmsg(bytes(message, 'utf-8')) error = fs.receivemsg() write_file = True if error == b'overwrite': while (True): overwrite = 'y' #input('A file with the same name already exists in the server, save as a copy? (y/n)\n') if overwrite == 'y': break elif overwrite == 'n': write_file = False break fs.sendmsg(bytes(overwrite, 'utf-8')) if write_file: f = open(split_message[1], 'r') contents = f.read() f.close() fs.sendmsg(bytes(split_message[1], 'utf-8')) message = contents else: #if file does not exist, ask the user for another input print('The file ' + split_message[1] + ' does not exist') # continue b_message = bytes(message, 'utf-8') fs.sendmsg(b_message) print("received:", fs.receivemsg())
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) user_input = input( 'What is the name of the file you would like to send?') try: f = open(user_input, 'rb') except: print( 'Error while opening file, make sure that it exists and is in the current directory' ) print('Sending file to server') user_input = bytearray(user_input, 'utf-8') fs.sendmsg(user_input) line = f.read(100) while (line): fs.sendmsg(bytearray(line)) line = f.read(100) try: print("received:", fs.receivemsg()) except: print('Error while receiving')
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) try: file = input("File name? \n") f = open(file, 'r') fs.sendmsg('FOF'.encode()) # to open the file to start writing print("received:", fs.receivemsg()) while True: line = f.read(100) print(line) line = line.strip() line = line.encode() if not line: break fs.sendmsg(line) print("received:", fs.receivemsg()) except FileNotFoundError: print('File not Found') sys.exit(1)
class ServerThread(Thread): requestCount = 0 # one instance / class lock = threading.Lock() # Shared lock to synchronize threads def __init__(self, sock, debug): Thread.__init__(self, daemon=True) self.fsock, self.debug = FramedStreamSock(sock, debug), debug self.start() def run(self): ServerThread.lock.acquire() # Try to get the lock try: while True: msg = self.fsock.receivemsg() # Receive client request if not msg: if self.debug: print(self.fsock, "server thread done") return requestNum = ServerThread.requestCount time.sleep(0.001) ServerThread.requestCount = requestNum + 1 if debug: print("rec'd: ", msg) if os.path.exists( msg): # Check if the file is in the server already. if debug: print("FILE ALREADY EXISTS") self.fsock.sendmsg(b"File exists") # Send the file exists. return else: self.fsock.sendmsg( b"Ready" ) # Send the server is ready to receive the file. with open(msg, 'w') as file: # Open file to receive if debug: print("OPENED FILE") while True: msg = self.fsock.receivemsg() # Receive the file. if debug: print("RECEIVED PAYLOAD: %s" % msg) if not msg: # Check if done receiving file. if debug: print("DONE WRITING INSIDE NOT MSG") return else: file.write(msg.decode() ) # Write the data to the file. if debug: print("WROTE THE PAYLOAD TO FILE") finally: ServerThread.lock.release( ) # Release the lock for the next thread.
def run(self): mutex.acquire() 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) fileSend = FramedStreamSock(s, debug=debug) while True: fileName = input( "What is the name of the file? (Use extensions): ") try: readFile = open(fileName, "r") break except FileNotFoundError as fileError: print(fileError) print("Please try again.") fileName = fileName.encode() fileSend.sendmsg(fileName) for line in readFile: line = line.strip() line = line.encode() fileSend.sendmsg(line) readFile.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)
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) while (1): try: fname = input("Please input name or 'exit' to end process:\n") if (fname == "exit"): os._exit(1) myFile = open(fname, 'r') mlock.release() break except IOError: print("File doesn't exist, try again.") auxStr = myFile.read().replace( "\n", "\0") #replace new lines to null characters myFile.close() auxStr = fname + "//myname" + auxStr + '\n' #Added the //myname to distinguish between file name and body fs.sendmsg(auxStr.encode()) fs.receivemsg() #Just to make sure the message is sent
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' )
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) filename = input("Choose file: ") try: with open(filename, "r") as myfile: data = myfile.read().replace('\n', '') except IOError: # FileNotFoundError print("File not found: {}".format(filename)) sys.exit() if not data: print("File is empty!") sys.exit() print("sending file") fs.sendmsg(data)
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) fname = self.fileName #input("please enter name of file to send to server: ") files = [f for f in os.listdir('.') if os.path.isfile(f)] #determine if file exists for sending for f in files: if f == fname: #sendName(fname) break else: print( "file for sending not found exiting") #if file not found exit sys.exit(0) print("sending file") fs.sendmsg(fname) #otherwise send file to server
def client_fork(): while True: from framedSock import FramedStreamSock sock, addr = lsock.accept() print("connection rec'd from", addr) ServerThread(sock, debug) fsock = FramedStreamSock(sock, debug) data = sock.recv(100) if not data: # check if data is being recieved break # check if connection still exists while (data): # while data is being sent file_out.write(data) data = fsock.recv(100) file_out.close() fsock.sendmsg(b'Finished transfer') fsock.close()
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) fileName = input('Enter file to transfer') try: filetoTransfer = open(fileName, 'rb') fileToTransfer.close() except: print('File Not Found. Error 404') sys.exit(1) print("Sending %s" % fileName) fs.sendmsg(fileName.encode()) f = open(fileName, 'rb') msg = f.read(100) while (msg): fs.sendmsg(msg) msg = f.read(100)
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() print(msg) if not msg: if self.debug: print(self.fsock, "server thread done") return if msg.decode() == 'FOF': f = open('Server_file.txt', 'w') msg = msg.decode() f.write(msg) msg = msg.encode() self.fsock.sendmsg(msg)
def run(self): global fileName 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 hello world") fs.sendmsg(b"hello world") print("received:", fs.receivemsg()) fs.sendmsg(b"hello world") print("received:", fs.receivemsg()) if os.path.isfile(fileName):#Check if file exists fileR = open(fileName, "rb") fileName1 = "IFL$" +fileName # IFL$ To let the server know it is a file fs.sendmsg(fileName1.encode())# Send file name receiveP = fs.receivemsg() print("received: ", receiveP) if receiveP.decode() != "File already in server": read = fileR.read(100) while read: read = read.decode().strip().encode() fs.sendmsg(read) print("received: ", fs.receivemsg()) read = fileR.read(100) fileR.close()
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) cF, oF = self.getCommand() fT = self.getPayload(cF) fs.getLock() oF = self.getOutputFile(oF) fs.sendmsg(oF) # sending output file #while fT: # curSend = fT[0:100] # fT = fT[100:] fs.sendmsg(fT) # sending payload fs.clearLock()