Exemple #1
0
def worker(addr, message):
    print("chegou aqui")

    sockd = socket(AF_INET, SOCK_DGRAM)

    args = message.decode().split()

    print("received Option: ", args[0])

    if (args[0] == "LST"):

        sockd.sendto("ACK".encode(), addr)

        files = ""

        path = pathlib.Path('tests')

        #Verificamos cada arquivo dentro da pasta especificada
        for currentFile in path.iterdir():
            files = files + str(currentFile) + "\n"
            #print(files)

        sockd.sendto(files.encode(), addr)

        print('Lista:', files)

    elif (args[0] == "GET"):

        sockd.sendto("ACK".encode(), addr)
        msg = "tests/" + args[1]
        utils.sendFile(sockd, msg, addr)
        print("Returned to main")
        #sockd.setblocking(True)

    print("Thread returning to main")
Exemple #2
0
def Main():
    #criando o socket de comunicação cliente servidor
    sockd = socket(AF_INET, SOCK_DGRAM)

    sockd.bind(('', UDP_PORT))

    print("Server is on")

    while True:
        #connectionSocket, addr = sockd.accept()
        messageFromClient, addr = sockd.recvfrom(1024)

        args = messageFromClient.decode().split()

        print("received Option: ", args[0])

        if (args[0] == "GET"):
            sockd.sendto("ACK".encode(), addr)
            msg = args[1]
            utils.sendFile(sockd, msg, addr)
            print("Returned to main")
            sockd.setblocking(True)

    print("Farewell")
    sockd.close()
Exemple #3
0
 def send(self, filepath, host, port):
     # assume file can be in memory
     with open(filepath,'r') as f:
         filedata =f.read()
     print "sending"
     filepath_name = filepath.rsplit(os.sep,1)
     # select the filename, if len = 0, then filepath_name = filename
     filename = filepath_name[len(filepath_name)-1]
     util.sendFile(filename, filedata, host, port)
def handleSend(controlSocket, filename):
    if not filename:
        print('  '.join(os.listdir('./files')))
    elif not os.path.isfile('./files/' + filename):
        print('File not found, cannot send: ', filename)
    else:
        listenSocket = utils.createTcpSocket(utils.PORT_X)
        listenSocket.listen(1)

        utils.sendCmdPacket(controlSocket, utils.SEND, filename)

        dataSocket, serverIpPort = listenSocket.accept()
        utils.sendFile(dataSocket, filename)

        print('File sent to server')
Exemple #5
0
def handleRequest(conn: socket.socket) -> int:
    # receive request method
    try:
        request_header = eval(utils.recvMessage(conn))
    except SyntaxError:
        print("ERROR while receiving header")
        return 1

    # handle request
    if request_header["method"] == "list":
        utils.sendMessage(conn, os.listdir(), message_len=const.HUGE_MESSAGE)
    elif request_header["method"] == "post":
        utils.recvFile(conn, request_header["filename"])
    elif request_header["method"] == "get":
        utils.sendFile(conn, request_header["filename"])
    # shouldn't get here
    else:
        print("ERROR: unknown metehod.")
	def _protocol_GET(self, matchObj):
		"""Handler for the GET command: Downloads a file from the server."""
		
		fileName = matchObj.group("filename")
		if isdir(fileName):
			sendStr(self._connSock, "ERR FILE IS A DIRECTORY\n")
		elif not isfile(fileName):
			sendStr(self._connSock, "ERR FILE DOES NOT EXIST\n")
		else:
			fileSize = getsize(fileName)
			debugPrint("SERVER: Sending {fname}".format(fname=fileName))
			try:
				sendStr(self._connSock, "READY {size}\n".format(size=fileSize))
				sendFile(self._dataSock, fileName, self._config["chunk_size"])
			except (PermissionError, IOError):
				sendStr(self._connSock, "ERR CANNOT READ FILE\n")
			else:
				sendStr(self._connSock, "OK {size}\n".format(size=fileSize))
def sendRequest(sock: socket.socket, request_header: dict) -> int:
    """Send request to a connected socket."""
    # send request header, pass possible error
    if utils.sendMessage(sock, str(request_header)) == 1:
        return 1

    # make request
    if request_header["method"] == "list":
        utils.printList(
            eval(utils.recvMessage(sock, message_len=const.HUGE_MESSAGE)))
    # check if filename argument is given
    elif not request_header["filename"]:
        print("ERROR: filename argument required for get/post")
    elif request_header["method"] == "post":
        utils.sendFile(sock, request_header["filename"])
    elif request_header["method"] == "get":
        utils.recvFile(sock, request_header["filename"])
    # shouldn't get here
    else:
        print("ERROR: unknown metehod.")
	def _command_PUT(self, matchObj):
		"""Handler for PUT command: Uploads a file to the server."""
		
		fileName = matchObj.group("filename")
		chunkSize = self._config["chunk_size"]
		
		if isdir(fileName):
			print("FAILURE: Cannot upload a directory.")
		elif not isfile(fileName):
			print("FAILURE: The file does not exist.")
		else:
			fileSize = getsize(fileName)
			sendStr(self._connSock, "PUT {size} {name}\n".format(size=fileSize, name=fileName))
			isReady = recvLine(self._connSock)
			if isError(isReady):
				return
			
			if isReady != "READY {size}".format(size=fileSize):
				if not self._isSocketClosed(isReady):
					debugPrint("CLIENT FAILURE: Malformed PUT reply from server.")
					return
			
			try:
				with Timer() as xferTime:
					sendFile(self._dataSock, fileName, chunkSize)
			except (PermissionError, IOError):
				print("CLIENT FAILURE: Cannot read from file.")
			else:
				isSent = recvLine(self._connSock)
				if isSent != "OK {size}".format(size=fileSize):
					if not self._isSocketClosed(isSent):
						debugPrint("CLIENT FAILURE: Malformed PUT reply from server.")
				else:
					print("SUCCESS: {name} ({size} byte{s}) uploaded in {secs:.4f} seconds.".format(
							name=fileName, size=fileSize, secs=xferTime.elapsedTime(), 
							s=("s" if fileSize > 1 else "")))