【问题标题】:Python transmitting a file over socketsPython 通过套接字传输文件
【发布时间】:2016-05-16 06:46:05
【问题描述】:

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

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

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

【问题讨论】:

  • 如果文件包含DONE会发生什么会很有趣。
  • 这是为了转移我编写的已编译的 C 程序,所以这不可能适得其反

标签: python sockets


【解决方案1】:

尝试在data = client_socket.recv(1024) 之后打印data 的值 您可能会看到类似:"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 行,它将不起作用;并且像这样在服务器上拆分行是低效的。 更好的方法是让客户端宣布文件的大小,然后继续发送它,这样服务器就知道何时停止读取。

【讨论】:

  • 我已经尝试过您的代码示例,但它并没有真正解决问题但是,您更改协议的建议听起来不错,所以我会尝试一下!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多