【问题标题】:Why isn't my client receiving my file from the server?为什么我的客户没有从服务器接收我的文件?
【发布时间】:2017-06-03 09:12:20
【问题描述】:

我创建了一个相当简单的服务器,目的是发送一个简单的 .txt 文件,但由于某种原因它不会发送。

服务器代码:

import socket

port = 8081
host = "192.168.0.20"
s = socket.socket()
s.bind((host, port))

s.listen(5)

print("Server Listening.....")

while True:
    conn, addr = s.accept()
    print("Got connection from", addr)
    data = conn.recv(1024)
    print("Data recieved", repr(data))

    filename = "/Users/dylanrichards/Desktop/keysyms.txt"
    f = open(filename, 'rb')
    l = f.read(1024)
    while (l):
        conn.send(l)
        print("Sent", repr(l))
        l = f.read(1024)
    f.close()

    print("Done sending")
    conn.send("Thank you for connecting")
    conn.close()

这是客户端的代码:

import socket

port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))

with open("Recieved_File", 'wb') as f:
    print("File opened")
    while True:
        print("Receiving data...")
        data = s.recv(1024)
        print("Data=%s",  (data))
        if not data:
            break
        f = open("/Users/dylanrichards/Desktop/test12.txt")
        f.write(data)

f.close()
print("Successfully got file")
print("Connection closed")
s.close()

如果有帮助的话,我会在 Macbook Air 上通过我的本地网络进行测试。在此先感谢...

【问题讨论】:

  • 我会尝试更改端口号。如果它有效,那是因为之前的端口已经分配了。
  • @Jean-FrançoisFabre,那是我认为可能的解决方案,但我已经尝试了很多次都无济于事
  • 好的,让网络专家来解答。我没有资格:) 你能更具体一点:是客户端没有发送,还是服务器没有接收?
  • 顺便说一句,您的接收有问题:您正在以read 模式打开test12.txt(从Received_File 覆盖您的f)并写信给它。那是假的。
  • 好的,所以我刚刚注意到它不是网络。在我的桌面上创建了一个文件,但没有任何数据。

标签: python networking server


【解决方案1】:
  1. 打开了多个文件句柄并且都具有相同的变量f
  2. with open("Recieved_File", 'wb') as f: -- 我认为这不是必需的。
  3. f = open("/Users/dylanrichards/Desktop/test12.txt")应该在while循环之外。
  4. 打开上述文件时,将模式添加为“wb”

客户端代码

import socket

port = 8081
host = "192.168.0.20"
s = socket.socket()
s.connect((host, port))

f = open("/Users/dylanrichards/Desktop/test12.txt",'wb')
while True:
    print("Receiving data...")
    data = s.recv(1024)

    if not data:
        break
    print("Data=%s",  (data))
    f.write(data)

f.close()
print("Successfully got file")
print("Connection closed")
s.close()

【讨论】:

  • 我已经尝试了您的代码,但数据仍然没有写入指定文件。服务器代码有问题吗?
  • 是的,其实你的服务器只有在收到一些数据的时候才会给出文件的内容;)
  • 只需在客户端连接前添加:s.send(bytes('Hello', 'utf-8')) ;)
  • 或者尝试从服务器中删除data = conn.recv(1024) 行。它等待来自客户端的一些数据。但是,您的客户端从未发送任何数据,因此,这一行阻塞了所有内容。
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 2014-07-05
  • 1970-01-01
  • 2019-12-27
  • 2017-12-29
  • 2022-01-09
  • 2021-01-28
相关资源
最近更新 更多