【问题标题】:Python TCP File Transmission over Client Server客户端服务器上的 Python TCP 文件传输
【发布时间】:2015-01-15 16:58:10
【问题描述】:

我有以下代码应该根据客户端发送到服务器的信息将文件发送到客户端。客户端将发送一个特定名称的应用请求。服务器将获取文件并将其发送给客户端。问题是服务器发送以下消息:

Not a heartbeat
No valid Message
App request Done
Done Sending Files

但是即使服务器完成发送文件,客户端也在监听文件。

服务器代码为here。客户端代码给here

我的代码做错了什么?

【问题讨论】:

  • 我不擅长网络的东西,但我认为你必须先发送文件的大小,然后让客户端在那么多字节后停止接收。
  • 客户端如何知道文件接收完毕?记住 socket.recv() 是一个阻塞调用。

标签: python python-2.7 tcp


【解决方案1】:

您可以通过在发送文件内容之前发送文件的总长度来实现。 并首先接收长度并读取到该长度

有效的代码sn-p如下

在服务器端(server.py)

   try:
        if data["app"]:
            print "App request Done"
            file_len =  os.stat("test_app.dll").st_size
            print data["app"]
            first_flag = True
            with open("test_app.dll", "rb") as ff:
                l = ff.read(2000)
                while(l):
                    if first_flag:
                        conn.send("test_app"+"#"+str(file_len)+"#"+l)
                        first_flag = False
                    else:
                        conn.send(l)
                    l = ff.read(2000)

            print "Done Sending Files"
    except Exception, e:
        print "Not a APP Request:",  e

在客户端:

while True:
    print "Sending App Request"
    s.sendall("{'app':'windows_process_monitor', 'platform':'windows'}")
    print "Receiving Files"

    first_flag = True
    with open("windows_process_monitor.dll", "wb") as dd:
        app_len = 0
        remaining_part_len = 0

        while(True):
            data = s.recv(1024)
            print data
            if not data:
                break
            if first_flag:
                app_name, app_len_str, first_part_content = data.split("#", 2)
                app_len += int(app_len_str)
                remaining_part_len += app_len
                first_received_len = len(first_part_content)
                dd.write(first_part_content)
                first_flag = False
                if app_len <= first_received_len:
                    print "all received"
                    break
                remaining_part_len -= first_received_len
            else:
                dd.write(data)
                remaining_part_len -= 1024
            if remaining_part_len <= 0:
                break
            print "inside while"

    print "Received ", repr(data)
    break

【讨论】:

  • 您必须删除无效 msg 返回类型中的 {success:false}。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多