【发布时间】:2015-08-03 19:19:28
【问题描述】:
我有一个服务器,它应该向客户端询问文件,压缩它并将其发送给客户端。我在将 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()
【问题讨论】:
-
您发送到服务器的内容是什么?文件路径?还是文件目录的路径?
-
我将路径发送到带有文件的目录。我想压缩目录(包括其中的文件)并将其作为 zip 文件发送给客户端。
标签: python unicode tcp network-programming zip