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)
コード例 #2
0
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)
コード例 #3
0
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)
コード例 #5
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)

        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)
 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
コード例 #7
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)
        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()
コード例 #8
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)

        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.....")
コード例 #9
0
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)
コード例 #10
0
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()
コード例 #11
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)
        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:])
コード例 #12
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)
        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.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)
コード例 #15
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)
        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()
コード例 #16
0
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)
コード例 #17
0
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)
コード例 #18
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)
コード例 #19
0
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)
コード例 #20
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)
        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.....")    
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)
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)
コード例 #23
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)
        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)
コード例 #24
0
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)
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:
            try:
                file_name, file_contents = self.fsock.receive(debug)
            except:
                print("Error: failure to transfer file")
                sys.exit(1)
            if debug: print("rec'd: ", file_name)
            if file_name is None:
                print("Error: file name is empty")
                sys.exit(1)
            if file_contents is None:
                print("Error: file contents are empty" )
                sys.exit(1)
            file_name = file_name.decode()
            start_file_transfer(file_name)
            self.write_file(file_name, file_contents)
            end_file_transfer(file_name)

    def write_file(self, file_name, file_contents):
        try:
            if(os.path.exists("./output/"+file_name)):
                print("file with name already exists.")
                sys.exit(1)
            else:
                print("Receiving "  +file_name)
                file_rec = open("./output/"+file_name,"wb")
                file_rec.write(file_contents)
                file_rec.close()
        except FileNotFoundError:
            print("Error: File Not Found")
            sys.exit(1)
    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
コード例 #29
0
    print("Can't parse server:port from '%s'" % server)
    sys.exit(1)

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))
############################################
print(
    "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)
############################################
コード例 #30
0
except:
    print("Cant parse server: port from '%s'" % server)
    sys.exit(1)

addrFamily = socket.AF_INTET
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))
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)