Python - 接收多个文件

时间:2018-03-30 19:37:56

标签: python file sockets server client

我正在学习套接字编程和Python,我需要创建一个从客户端接受多个文件的服务器。 当我收到其中一个文件时,我收到此错误:

ValueError: invalid literal for int() with base 2: '<!DOCTYPE html PUBLIC "-//W3C//D'

我不明白为什么! 谢谢你的帮助!

client.py

for files in directory:
        try:
            print files
            filename = files
            size = len(filename)
            size = bin(size)[2:].zfill(16) 
            s.send(size)
            s.send(filename)

            filename = os.path.join(path,filename)
            filesize = os.path.getsize(filename)
            filesize = bin(filesize)[2:].zfill(32) #
            s.send(filesize)

            file_to_send = open(filename, 'rb')

            l = file_to_send.read()
            s.sendall(l)
            file_to_send.close()
            print 'File Sent'
        except socket.error, e:
            print "Error sending data: %s" % e

server.py

while True:
       size = clientsocket.recv(16)
       if not size:
           break
       size = int(size)
       filename = clientsocket.recv(size)
       filesize = clientsocket.recv(32)
       filesize = int(filesize,2)
       file_to_write = open("/home/giorgio/Scrivania/SERVER/Download/"+'new_'+filename, 'wb')
       num_files += 1
       chunksize = 1024
       while filesize > 0:
           if filesize < chunksize:
               chunksize = filesize
           data = clientsocket.recv(chunksize)
           file_to_write.write(data)
           filesize -= len(data)

       file_to_write.close()
       print 'File received successfully'


serversock.close()

1 个答案:

答案 0 :(得分:0)

while True:
       size = clientsocket.recv(16)
       if not size:
           break
       size = int(size)
       filename = clientsocket.recv(size)
       filesize = clientsocket.recv(32)
       #filesize = int(filesize,2) #This is not required and this is causing the error so remove it.
       file_to_write = open("/home/giorgio/Scrivania/SERVER/Download/"+'new_'+filename, 'wb')
       num_files += 1
       chunksize = 1024
       while filesize !="": #update to empty string comparison 
           if filesize < chunksize:
               chunksize = filesize
           data = clientsocket.recv(chunksize)
           file_to_write.write(data)
           filesize = len(data)

       file_to_write.close()
       print 'File received successfully'


serversock.close()

我已为您添加评论以查看可能的修复方法。