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):
        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()
Beispiel #3
0
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.
Beispiel #4
0
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)
Beispiel #5
0
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()
Beispiel #6
0
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()
Beispiel #7
0
    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())
Beispiel #8
0
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):
        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)
Beispiel #10
0
    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())
Beispiel #11
0
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):
        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
Beispiel #13
0
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.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)
Beispiel #15
0
    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")
Beispiel #16
0
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)
    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)
       cmd = input('ftp$ ')
       para = cmd.split()
       #para = ('put', 'whygrep')
       if (len(para) == 2 and para[0] == 'put'):#check if put in filename
           try:
               print('atpara1')
               print(para[1])
               file = open(para[1], 'rb')

           except:
               print('file not found')
               exit(0)
           filenam = './' + para[1]  # send filename
           fs.sendmsg(filenam.encode())
           print("received:", fs.receivemsg())
           while True:  # read file

               data = file.read(100)  # .encode()
               print(data)
               if not data:  # end of file
                   fs.sendmsg(b"~")
                   print("received:", fs.receivemsg())
                   return
               fs.sendmsg(data)#.encode())  # send file by 100 byte increments
               print("received:", fs.receivemsg())
       else:
           print('no command or missing parameter')
    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()
Beispiel #19
0
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)
Beispiel #21
0
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 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)
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()
Beispiel #24
0
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.
Beispiel #25
0
    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
    def __init__(self, sock, debug):
        Thread.__init__(self, daemon=True)
        self.fsock, self.debug = FramedStreamSock(sock, debug), debug
        self.start()
        lock = threading.lock()

    def run(self):
        while True:
            lock.acquire()

            payload = self.fsock.receivemsg()

            if not payload:
                if self.debug: print(self.fsock, "server thread done")
                else print("client disconnected unexpectedly")
                lock.release()
                return

            if "sdsf" in payload.decode():
                print("Client in port %s exiting..." % addr[1])
                sys.exit(0)

            data = re.split(" ", payload.decode())

            if "put" in data[0]:
                if not open(data[1], "rb"):
                    f = open(data[1], "wb")
                    f.write(data[2])
                    f.close()
                    print("File received.")
                else:
                    #addcode here
                    print("File already exists in server!")
                    self.fsock.sendmsg(sock, b"sdsf", 1)

            elif "get" in data[0]:
                print("File request received.")

                try:
                    f = open(data[1], "rb")
                except FileNotFoundError:
                    print("File not found.")
                    self.fsock.sendmsg(sock, b"sdsf", 1)
                    continue

                if os.stat(data[1]).st_size == 0:
                    framedSend(sock, b"empty", -1)
                    f.close()
                    print("Error, file is empty.")
                    continue

                    self.fsock.sendmsg(sock, f.read(), -1)
                f.close()
                print("File sent.")

            if debug: print("rec'd: ", payload)
            lock.release()
Beispiel #27
0
class ServerThread(Thread):
    requestCount = 0  # one instance / class
    mutex = Lock()

    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:
            ServerThread.mutex.acquire()
            print("Mutex acquired")
            try:
                msg = self.fsock.receivemsg()
                if not msg:
                    if self.debug: print(self.fsock, "server thread done")
                    return
                filename = msg.decode()
                if os.path.exists('server-files/' + filename):
                    print("File already exists on server")
                    self.fsock.sendmsg(b"Error: File already exists on server")
                    #framedSend(sock, b"Error: File already exists on server", debug)
                    return
                requestNum = ServerThread.requestCount
                time.sleep(0.001)
                ServerThread.requestCount = requestNum + 1
                #msg = ("%s! (%d)" % (msg, requestNum)).encode()
                #self.fsock.sendmsg(msg)
                self.fsock.sendmsg(b"SUCCESS")
                #framedSend(sock, b"SUCCESS", debug)
                f = open('server-files/' + filename, "wb")
                #line = framedReceive(sock, debug)
                line = self.fsock.receivemsg()
                while (line.decode() != "done"):
                    print("Server line: " + line.decode())
                    f.write(line)
                    #time.sleep(0.001)
                    #line = framedReceive(sock, debug)
                    line = self.fsock.receivemsg()
                f.close()
                #framedSend(sock, payload, debug)
                self.fsock.sendmsg(msg)
            finally:
                ServerThread.mutex.release()
                print("Mutex released")
    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())
Beispiel #29
0
    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
    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.