我想用Python编写一个程序,在套接字上传输文件夹中的多个文件,我目前有以下代码:
客户端:
def uploadFiles(folder,dcip,PORT,filetype):
os.chdir(folder)
dirList = os.listdir(folder)
print dirList
ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print PORT
ms.connect((dcip, int(PORT)))
for fname in dirList:
if fname.endswith(str(filetype)):
cmd = 'get\n%s\n' % (fname)
ms.sendall(cmd)
f = open(fname,'rb')
data = f.read()
f.close()
print data
r = ms.recv(2)
ms.sendall(data)
ms.sendall('done\n%s\n' %(fname))
ms.sendall('end\n\n')
ms.close()
服务器:
import socket,os
listener_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener_socket.bind(('',33234))
filename = ''
while 1:
listener_socket.listen(100)
connection,address_client = listener_socket.accept()
if not os.path.exists(str(address_client[0])):
os.makedirs(str(address_client[0]))
currdir = os.getcwd()
os.chdir('./'+str(address_client[0]))
while(1):
data = connection.recv(4096)
cmd = data[:data.find('\n')]
if cmd == 'get':
x,filename,x = data.split('\n',2)
connection.sendall('ok')
f = open(filename,'wb')
if cmd == 'done':
continue
f.write(data)
if cmd == 'end':
connection.close()
break
os.chdir(currdir)
上面的代码进入了一个无限循环,我知道这是因为在 if cmd == 'done'
部分中有一个 continue 语句,但我不明白为什么会这样?我的意思是它从来没有收到来自客户端的 done 消息,有人能帮我修复代码吗?