Ejemplo n.º 1
0
def client():
    switchesVarDefaults = (
        (('-s', '--server'), 'server', "127.0.0.1:50001"),
        (('-d', '--debug'), "debug", False),  # boolean (set if present)
        (('-?', '--usage'), "usage", False),  # boolean (set if present)
    )

    paramMap = params.parseParams(switchesVarDefaults)

    server, usage, debug = paramMap["server"], paramMap["usage"], paramMap[
        "debug"]

    if usage:
        params.usage()

    try:
        serverHost, serverPort = re.split(":", server)
        serverPort = int(serverPort)
    except:
        print("can't parse server:port from '%s'" % server)
        sys.exit(1)

    addr_port = (serverHost, serverPort)

    # create socket object
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.connect(addr_port)

    # create encapsulated socket
    encap_socket = EncapFramedSock((listen_socket, addr_port))

    while True:
        filename = input("Enter the file to be sent: ")
        filename.strip()

        if filename == "exit":
            sys.exit(0)
        else:
            if not filename:
                continue
            elif os.path.exists(PATH_FILES + filename):
                # open file and read
                file = open(PATH_FILES + filename, "rb")
                file_content = file.read()

                # verify file is not empty before sending
                if len(file_content) < 1:
                    print(EMPTY_MSG % filename)
                    continue

                # send file contents to server
                encap_socket.send(filename, file_content, debug)

                # check if server received file
                status = encap_socket.get_status()
                status = int(status.decode())

                # successful transfer
                if status:
                    print(CONFIRM_MSG % filename)
                    sys.exit(0)
                # failed transfer
                else:
                    print(REJECT_MSG % filename)
                    sys.exit(1)

            # file not found
            else:
                print("ERROR: file %s not found. Try again" % filename)
from socket import *

import re
import params

switchesVarDefaults = (
    (('-l', '--listenPort') ,'listenPort', 50000),
    (('-d', '--debug'), "debug", False), # boolean (set if present)
    (('-?', '--usage'), "usage", False) # boolean (set if present)
    )

paramMap = params.parseParams(switchesVarDefaults)
listenPort, usage, debug = paramMap["listenPort"], paramMap["usage"], paramMap["debug"]

if usage:
    params.usage()

try:
    listenPort = int(listenPort)
except:
    print "Can't parse listen port from %s" % listenPort
    sys.exit(1)

sockNames = {}               # from socket to name
nextConnectionNumber = 0     # each connection is assigned a unique id

class Fwd:
    def __init__(self, conn, inSock, outSock, bufCap = 1000):
        self.conn, self.inSock, self.outSock, self.bufCap = conn, inSock, outSock, bufCap
        self.inClosed, self.buf = 0, ""
    def checkRead(self):
Ejemplo n.º 3
0
def client():
    switchesVarDefaults = (
        (('1', '--server'), 'server', "127.0.0.1:50001"),
        (('?', '--usage'), 'usage', False),
        (('d', '--debug'), 'debug', False),
    )

    # based on demos
    parameterMap = params.parseParams(switchesVarDefaults)
    server, usage, debug = parameterMap['server'], parameterMap[
        'usage'], parameterMap['debug']

    if usage:
        params.usage()

    try:
        serverHost, serverPort = re.split(":", server)
        serverPort = int(serverPort)
    except:
        print("Can't parse server:port from '%s'" % server)
        sys.exit(1)

    port = (serverHost, serverPort)

    # create socket
    listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listenSocket.connect(port)

    encapSocket = FramedSock((listenSocket, port))

    while 1:
        fileName = input("Enter a filename > ")
        fileName.strip()

        if fileName == "exit":  # terminate
            sys.exit(0)
        else:
            if not fileName:
                continue
            elif os.path.exists(PATH + fileName):
                f = open(PATH + fileName, "rb")  # read and binary
                contents = f.read()

                if len(contents) < 1:
                    print("Error: File %s is empty" % fileName)
                    continue

                encapSocket.send(fileName, contents, debug)

                # check if server was able to receive the file
                status = encapSocket.Status()
                status = int(status.decode())

                if status:
                    print("File %s received by server." % fileName)
                    sys.exit(0)
                else:
                    print(
                        "File Transfer Error: File %s was not received by server."
                        % fileName)
                    sys.exit(1)

            else:
                print("File Not Found Error: File %s not found!" % fileName)
Ejemplo n.º 4
0
def client():
    switchesVarDefaults = (
        (('-s', '--server'), 'server', "127.0.0.1:50001"),
        (('-d', '--debug'), "debug", False),  # boolean (set if present)
        (('-?', '--usage'), "usage", False),  # boolean (set if present)
    )

    paramMap = params.parseParams(switchesVarDefaults)

    server, usage, debug = paramMap["server"], paramMap["usage"], paramMap[
        "debug"]

    if usage:
        params.usage()

    try:
        serverHost, serverPort = re.split(":", server)
        serverPort = int(serverPort)
    except:
        print("Can't parse server:port from '%s'" % server)
        sys.exit(1)

    addr_port = (serverHost, serverPort)

    # create socket object
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listen_socket.connect(addr_port)

    while True:
        filename = input("> ")
        filename.strip()

        if filename == "exit":
            sys.exit(0)
        else:
            if not filename:
                continue
            elif os.path.exists(PATH_FILES + filename):
                # send file name
                listen_socket.sendall(filename.encode())
                file_content = open(PATH_FILES + filename, "rb")

                # send file size
                listen_socket.sendall(
                    str(os.stat(PATH_FILES + filename).st_size).encode())

                # send file content
                while True:
                    data = file_content.read(1024)
                    listen_socket.sendall(data)
                    if not data:
                        break
                file_content.close()

                # check if server received file
                status = int(listen_socket.recv(1024).decode())
                # successful transfer
                if status:
                    print(CONFIRM_MSG % filename)
                    sys.exit(0)
                # failed transfer
                else:
                    print(REJECT_MSG % filename)
                    sys.exit(1)
            # file not found
            else:
                print("ERROR: file %s not found" % filename)
Ejemplo n.º 5
0
import re, socket, params, os
from framedSock import framedSend, framedReceive

def destroyParams(debug, listenPort, usage, maxConnections):
    return debug, listenPort, usage, maxConnections # destructing dictionary

switchesVarDefaults = (
    (('-l', '--listenPort'), 'listenPort', 50001),
    (('-d', '--debug'), 'debug', False),
    (('-?', '--usage'), 'usage', False),
    (('-c', '--connections'), 'maxConnections', 5)
)

debug, listenPort, usage, maxConnections = destroyParams(**params.parseParams(switchesVarDefaults))

if usage: params.usage() # printing usage

lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
bindAddr = ('127.0.0.1', int(listenPort))
lsock.bind(bindAddr)
lsock.listen(maxConnections)
print('listening on:',bindAddr)

while True:
    sock, addr = lsock.accept()
    if not os.fork():
        print("new child process handling connection from", addr)
        while True:
            try:
                payload = framedReceive(sock, debug)
                if payload == b'': # means we've reached end
Ejemplo n.º 6
0
def server():
    switchesVarDefaults = (
        (('-l', '--listenPort'), 'listenPort', 50001),
        (('-d', '--debug'), "debug", False),  # boolean (set if present)
        (('-?', '--usage'), "usage", False),  # boolean (set if present)
    )

    paramMap = params.parseParams(switchesVarDefaults)
    debug, listenPort = paramMap['debug'], paramMap['listenPort']

    if paramMap['usage']:
        params.usage()
    bindAddr = (HOST, listenPort)

    # creating listening socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # bind socket to host and port number
    s.bind(bindAddr)

    s.listen(5)
    print("listening on: ", bindAddr)

    conn, addr = s.accept()
    print('Connection from: ', addr)
    lock = threading.Lock()

    class Server(Thread):
        def __init__(self, sockAddr):
            Thread.__init__(self)
            self.sock, self.addr = sockAddr
            self.fsock = encapFramedSock(sockAddr)

            def run(self):
                while True:
                    try:
                        fileName, fileContent = self.fsock.receive(debug)
                    except:
                        print("File transfer failed")
                        # send failed status
                        self.fsock.send_status(0, debug)
                        self.fsock.close()
                        sys.exit(1)
                    if debug:
                        print("Received", fileContent)

                    if fileName is None or fileContent is None:
                        print("Client %s has disconnected" % self.addr)
                        sys.exit(0)

                    lock.acquire()
                    if debug:
                        time.sleep(5)
                    try:
                        fileWriter = open(FILE_PATH + fileName.decode(), 'wb')
                        fileWriter.write(fileContent)
                        fileWriter.close()
                        print("File %s received from client %s" %
                              (fileName.decode(), addr))
                    except FileNotFoundError:
                        print("File %s not found" % fileName.decode())
                        sys.exit(1)
                    lock.release()
    if len(sys.argv) < 3:
        print("Wrong use of command or params, to send a file please use the following notation: ./fileClient.py put <sourceFile> <destinationFile> [params]")
        sys.exit(0)
    putIndex = sys.argv.index('put')
    put, source, destination = True, sys.argv[putIndex + 1], sys.argv[putIndex + 2]
    newArgv = sys.argv
    newArgv.remove('put')
    newArgv.remove(source)
    newArgv.remove(destination)
    sys.argv = newArgv  #resetting argv so that there are no errors when checking for params

import params # has to be imported until here since params runs code when imported therefore argv needs to be dealt with before importing.

server, debug, usage, proxy = destroyParams(**params.parseParams(switchesVarDefaults))

if usage: params.usage()

if put:
    try:
        serverHost, serverPort = re.split(':', ('127.0.0.1:50000' if proxy else server))
        serverPort = int(serverPort)
    except:
        print("Can't parse server:port from '%s'" % server)
        sys.exit(1)

    addrPort = (serverHost, serverPort)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    if sock is None:
        print('could not open socket')
        sys.exit(1)
def server():
    switchesVarDefaults = (
        (('-l', '--listenPort'), 'listenPort', 50001),
        (('-d', '--debug'), "debug", False),  # boolean (set if present)
        (('-?', '--usage'), "usage", False),  # boolean (set if present)
    )

    paramMap = params.parseParams(switchesVarDefaults)
    debug, listenPort = paramMap['debug'], paramMap['listenPort']

    if paramMap['usage']:
        params.usage()

    bind_addr = (HOST, listenPort)

    # creating listening socket
    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # associating socket with host and port number
    listen_socket.bind(bind_addr)

    # "makes" listening socket with max connection to 5
    listen_socket.listen(5)
    print("listening on: ", bind_addr)

    # move to directory to receive files
    os.chdir(PATH_FILES)

    while True:
        # connection and tuple for client address (host, port)
        conn, addr = listen_socket.accept()

        # check connection and client address exist otherwise exit
        if not conn or not addr:
            sys.exit(1)

        if not os.fork():
            print("connection rec'd from", addr)
            # receive file name first
            data = conn.recv(1024)
            filename = data.decode()

            # file byte size
            data_byte = conn.recv(1024).decode()
            try:
                data_byte = int(data_byte)
            except ValueError:
                print("ERROR: byte size not received")
                # send failed status
                conn.sendall(str(0).encode())
                sys.exit(1)

            # if filename was provided, write it
            if filename:
                write_file(filename, data_byte, conn, addr)
                # send successful status
                conn.sendall(str(1).encode())
                sys.exit(0)
            else:
                print("ERROR: empty filename")
                # send failed status
                conn.sendall(str(0).encode())
                sys.exit(1)
Ejemplo n.º 9
0
def send_file():
    switchesVarDefaults = ( 
        (('-s', '--server'), 'server', "127.0.0.1:50000"),
        (('-f', '--file'), 'filename', 'testfile'),
        (('-r', '--remote'), 'filename_r','testfile'), 
        (('-d', '--debug'), "debug", False),
        (('-?', '--usage'), "usage", False), # boolean (set if present)
        )

    progname = "file_transfer_client"
    paramMap = params.parseParams(switchesVarDefaults)

    server, usage, filename, debug, filename_r = paramMap["server"], paramMap["usage"], paramMap["filename"], paramMap["debug"], paramMap["filename_r"] #Getting parameters usage from args

    if usage:
        params.usage()

    try: #Tries to parse server name 
        serverHost, serverPort = re.split(":", server)
        serverPort = int(serverPort)
    except:
        print("Can't parse server:port from '%s'" % server)
        sys.exit(1)

    addrFamily = socket.AF_INET #Creates socket 
    socktype = socket.SOCK_STREAM
    addrPort = (serverHost, serverPort)
    sock = socket.socket(addrFamily, socktype)

    if sock is None: #If cannot open socket
        print("Could not open socket!")
        sys.exit(1)

    sock.connect(addrPort)

    if os.stat(filename).st_size == 0: #Checks if file is empty and rejects it
        print("No zero length files allowed. Try again.")
        sock.close()
        sys.exit(1)

    file_size = os.path.getsize(filename) #Gets file size 

    if filename_r == "testfile": #If remote usage is default 
        filename_r = filename

    framedSend(sock, bytes(filename_r + ":" + str(file_size), 'utf-8'), debug) #Sends filename to server
    file_exists = framedReceive(sock, debug) #Gets response from server if file exists
    print("Sending file: '" + filename + "', Remote name: '" + filename_r + "'")

    if file_exists == b'1': #If file exists on server
        print("File exists. Will override...")

    try: 
        with open(filename, 'rb') as file: #Opens file to read
            while True:
                data = file.read(16384) #Reads file by 16384 bytes (16kB)
                framedSend(sock, data, debug) #Sends data

                if not data: #Breaks if data is None type
                    break

                data_sent = framedReceive(sock, debug) #Saves server response

                if data != data_sent: #Checks if response from the server is a complete message
                    print("Transfer failed! Connection was dropped or file active.")
                    file.close()
                    sock.close()
                    sys.exit(0)

                if debug:
                    print("Data sent: ", data_sent)

            print("File: '" + filename + "' sent!")
            file.close() #Closes file reader

    except FileNotFoundError: #If file is not found
        print("File not found. Try again.")

    sock.close()