我有一台服务器应该向客户端询问文件,压缩它并将其发送给客户端。我能够将zip文件发送到服务器有点麻烦。
这是我收到的错误:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/Users/Alcantara/Desktop/Final/Server.py", line 9, in RetrFile
for dirname, subdirs, files in os.walk(Zip):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 278, in walk
names = listdir(top)
TypeError: coercing to Unicode: need string or buffer, ZipFile found
这是我的服务器:
import socket
import threading
import os
import zipfile
def RetrFile(name, sock):
Zip = sock.recv(1024)
Zip = zipfile.ZipFile("new_" + Zip +".zip", "w")
for dirname, subdirs, files in os.walk(Zip):
Zip.write(dirname)
for filename in files:
Zip.write(os.path.join(dirname, filename))
Zip.close()
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
sock.close()
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print "Server Started."
while True:
c, addr = s.accept()
print "client connedted ip:<" + str(addr) + ">"
t = threading.Thread(target=RetrFile, args=("RetrThread", c))
t.start()
s.close()
if __name__ == '__main__':
Main()
客户端:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
filename = raw_input("Filename? -> ")
if filename != 'q':
s.send(filename)
f = open('new_'+filename, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print "{0:.2f}".format((totalRecv/float(filesize))*100)+ "% Done"
print "Download Complete!"
f.close()
else:
print "File Does Not Exist!"
s.close()
if __name__ == '__main__':
Main()
答案 0 :(得分:1)
考虑以下几点:
Zip = sock.recv(1024)
Zip = zipfile.ZipFile("new_" + Zip +".zip", "w")
for dirname, subdirs, files in os.walk(Zip):
您使用相同的变量名称来引用接收的数据(第1行和第3行)以及ZipFile
对象(第2行)。
请改为尝试:
#UNTESTED
zname = sock.recv(1024)
zfile = zipfile.ZipFile("new_" + Zip +".zip", "w")
for dirname, subdirs, files in os.walk(zname):
zfile.write(dirname)
for filename in files:
zfile.write(os.path.join(dirname, filename))
zfile.close()
with open("new_" + zname + ".zip", 'rb') as f:
# ... the rest is unchanged