服务器未接收Python中从客户端发送的所有文件

时间:2015-04-12 08:53:16

标签: python

我用Python编写了客户端和服务器代码。在代码中,客户端将路径作为用户的输入。路径可以是文件夹或文件。之后,客户端遍历该文件夹/目录并将其中的所有文件及其子文件夹中的所有文件发送到服务器,但问题是服务器只接收一个文件,尽管客户端正在将所有文件发送到服务器。 / p>

有什么问题?

客户代码:

from socket import *
import fnmatch
import os


serverIP = '10.99.26.144'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverIP, serverPort))
path = input('Input Path:')


if os.path.exists(path):
    clientSocket.send(bytes(path, 'UTF-8'))


    if os.path.isfile(path):
        file = open(path, "rb")
        data = file.read(1024)
        while (data):
            clientSocket.send(data)
            data = file.read(1024)
        file.close()

    else:
        for root, dirnames, filenames in os.walk(path):
            for filename in fnmatch.filter(filenames, '*.*'):
                print( os.path.join(root, filename).encode('utf-8') )
                clientSocket.send(os.path.join(root, filename).encode('utf-8'))
                file = open(root+"\\"+filename, "rb")
                data = file.read(1024)
                while (data):
                    clientSocket.send(data)
                    data = file.read(1024)
                file.close()
        clientSocket.send("".encode('utf-8'))

else:
    print("Path is invalid!")

clientSocket.close()
print("connection closed")

服务器代码:

from socket import *
import os


serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print('The server is ready to receive')
connectionSocket, address = serverSocket.accept()
path = connectionSocket.recv(1024)


if os.path.isfile(path):
    file = open(os.path.basename(path), 'wb') #Open in binary
    data = connectionSocket.recv(1024)
    while (data):
        file.write(data)
        data = connectionSocket.recv(1024)
    file.close()

else:
    while True:
        path = connectionSocket.recv(1024)
        print(path)
        if path.decode('utf-8')=="":
            break
        fileName = os.path.basename(path).decode('utf-8')
        drive, tail = os.path.splitdrive( os.path.dirname(path))
        directory = os.getcwd()+tail.decode('utf-8')
        if not os.path.exists(directory):
            os.makedirs(directory)

        file = open( directory + "\\" + fileName, 'wb') #Open in binary
        data = connectionSocket.recv(1024)
        while (data):
            file.write(data)
            data = connectionSocket.recv(1024)
        file.close()

connectionSocket.close()
print("connection closed")

2 个答案:

答案 0 :(得分:0)

所以,这里的问题是你只创建了一次文件(第一个文件)。然后将所有收到的内容(也是文件路径)写入同一个文件。

else:  
    while True:
        path = connectionSocket.recv(1024)
        print(path)
        if path.decode('utf-8')=="":
            break
        fileName = os.path.basename(path).decode('utf-8')
        drive, tail = os.path.splitdrive( os.path.dirname(path) )
        directory = os.getcwd()+tail.decode('utf-8')
        if not os.path.exists(directory):
            **os.makedirs(directory)**

在下面的while循环中,您只是将数据写入上面创建的文件

    while (data):
        file.write(data)
        data = connectionSocket.recv(1024)
    file.close()

您需要为上述while循环中的每次读取添加create new file。

答案 1 :(得分:0)

您可以使用此客户端和服务器以同步模式传输文件。传输按文件进行,当客户端向服务器发送数据时,它需要服务器的一些响应,这样我就创建了一些传输文件的协议。您可能需要根据需要修改一些语句。

我只针对多个文件进行了修改,请记住这一点。

<强>客户端:

from socket import *
import fnmatch
import os


serverIP = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverIP,serverPort))
path = raw_input('Input Path:')


if os.path.exists(path):
    clientSocket.send(bytes(path))
    path_resp = clientSocket.recv(1024)


    if os.path.isfile(path):
        file = open(path, "rb")
        data = file.read(1024)
        while (data):
            clientSocket.send(data)
            data = file.read(1024)
        file.close()


    else:
        file_list = []
        for root, dirnames, filenames in os.walk(path):
            for filename in fnmatch.filter(filenames, '*.*'):
                file_list.append(os.path.join(root, filename).encode('utf-8'))
        print file_list
        file_list = iter(file_list)
        while True:
            file_transfer_done = False
            try:
                file_name = file_list.next()
            except StopIteration, e:
                str(e)
                break

            print('Sent file name to server %s' % file_name)
            clientSocket.send(file_name)
            file_resp = clientSocket.recv(1024)
            print('Received server response : %s' % file_resp)
            file = open(file_name, "rb")
            data = file.read(1024)
            while True:
                if data:
                    clientSocket.send(data)
                    print('Sent data to server')
                    data_resp = clientSocket.recv(1024)
                    print('Received server responce : %s' % data_resp)
                data = file.read(1024)
                if not data:
                    clientSocket.send('file_closed')
                    close_resp = clientSocket.recv(1024)
                    break
            file.close()
        clientSocket.send("close".encode('utf-8'))


else:
    print("Path is invalid!")

clientSocket.close()
print("connection closed")

服务器

from socket import *
import os


serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
print('The server is ready to receive')
connectionSocket, address = serverSocket.accept()
path = connectionSocket.recv(1024)

connectionSocket.send('path_received')

if os.path.isfile(path):
    file = open(os.path.basename(path), 'wb' )
    data = connectionSocket.recv(1024)
    while (data):
        file.write(data)
        data = connectionSocket.recv(1024)
    file.close()


else:
    while True:
        path = connectionSocket.recv(1024)
        print('Received file from client: %s' % path)
        connectionSocket.send('file_path_received')
        print('Sent responce to client : %s' % ('file_path_received'))

        if path.decode('utf-8')=="":
            break
        fileName = os.path.basename(path)
        print('File name received : %s' % fileName)
        drive, tail = os.path.splitdrive( os.path.dirname(path) )
        directory = os.getcwd()+tail
        print directory
        if not os.path.exists(directory):
            os.makedirs(directory)

        file = open( directory +"/"+ fileName, 'wb' )
        print('New file created : %s' % fileName)
        data = connectionSocket.recv(1024)

        while True:
            file.write(data)
            print('File write done')
            connectionSocket.send('Processed')
            data = connectionSocket.recv(1024)
            if 'file_closed' in data:
                connectionSocket.send('file_done')
                break
        file.close()


connectionSocket.close()
print("connection closed")

注意:这是我尝试的示例代码,您可以做得更好。