基于TCP套接字的Python多文件传输

2024-10-01 15:48:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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()

服务器:

^{pr2}$

上面的代码进入了一个无限循环,我知道这是因为if cmd == 'done'部分中的continue语句,我想知道它为什么要这样做?我的意思是它从来没有收到客户端的“完成”消息,有人能帮我修改代码吗?在


Tags: 代码cmddataifosportsocketfolder
1条回答
网友
1楼 · 发布于 2024-10-01 15:48:44

因为命令和文件名在不同的行中,所以最好逐行解析接收到的数据。块数据的最后一部分不必以\n结束,因此它必须与下一个接收到的数据块合并。在

这是(未测试)按行解析接收数据的实现:

data = '' # contains last line of a read block if it didn't finish with \n
in_get, in_done, reading_file, ended = False, False, False, False
while not ended:
  if len(data) > 100:  # < update
    f.write( data )    # <
    data = ''          # <
  data += connection.recv(4096)
  i = data.find('\n')
  while i >= 0 and not ended:
    line = data[:i]
    data = data[i+1:]
    if in_get:
      filename = line
      reading_file = True
      f = open(filename,'wb')
      in_get = False
    elif in_done:
      if line != filename:  # done inside file content
        f.write( 'done\n' + line + '\n' )
      else:
        f.close()
        reading_file = False
      in_done = False
    else:
      if line == 'get' and not reading_file:
        in_get = True
      elif line == 'done':
        in_done = True
      elif line == 'end' and not reading_file:
        ended = True
        break;
      else:
        f.write( line + '\n' )
    i = data.find('\n')

相关问题 更多 >

    热门问题