为什么我的客户机没有从服务器接收到我的文件?

2024-04-20 13:58:24 发布

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

我创建了一个相当简单的服务器,目的是发送一个简单的.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()

如果有帮助的话,我会在macbookair的本地网络上测试这个。提前谢谢。。。你知道吗


Tags: 代码import服务器txttruehostclosedata
1条回答
网友
1楼 · 发布于 2024-04-20 13:58:24
  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()

相关问题 更多 >