Python通过套接字传输文件

时间:2016-05-15 22:36:45

标签: python sockets

我试图通过套接字传输文件,如果我在那之后立即关闭连接就可以正常工作 现在我想在上传完成后继续向服务器发送命令,但服务器只是忽略它们并认为文件有更多的行

到目前为止,这是我的代码 客户端:

def client_sender():
  global upload
  client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  try:
      print target
      print port
      client.connect((target, port))

      if upload:
          with open(upload_destination, "rb") as f:
              for line in f:
                  client.send(line)
          f.close()
          client.send("DONE\r\n")
          upload = False

      print client.recv(1024)
      buffer = ""
      buffer = sys.stdin.read()
#... some code for sending commands and receiving a response

服务器:

def handle_client(client_socket):
    global upload
    print "Client connected"
    if upload:
        file_buffer = ""
        while True:
            data = client_socket.recv(1024)
            if data.rstrip() == "DONE":
                break
            file_buffer += data
        try:
            file_descriptor = open(upload_destination, 'wb')
            file_descriptor.write(file_buffer)
            file_descriptor.close()

            client_socket.send("Successfully placed the file in %s" %upload_destination)
        except:
            client_socket.send("Failed writing to the file")

        upload = False
#... same as client, just some more code for commands

1 个答案:

答案 0 :(得分:3)

尝试在data之后打印data = client_socket.recv(1024)的值 您可能会看到类似的内容:"endofthefile\nDONE\r\n"

因此,当你对它运行rstrip时,你会得到:"endofthefile\nDONE",它不等于"DONE"

你应该像这样重写你的while循环:

    while True:
        data = client_socket.recv(1024)
        for line in data.split('\n'):
            if data.rstrip() == "DONE":
                break
            file_buffer += line + '\n'

您可能还希望在客户端使用此功能来宣布结束:client.sendall("DONE\r\n")sendall立即刷新客户端的缓冲区,而不是等待在同一个数据包中发送更多数据。

偏离主题,但我建议您更改协议。如果文件包含DONE行,它将无法工作;在这样的服务器上拆分行是没有效率的。 更好的方法是让客户端宣布文件的大小,然后继续发送它,这样服务器就知道何时停止阅读。