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

时间:2017-01-18 20:22:12

标签: python networking server

我创建了一个相当简单的服务器,目的是发送一个简单的.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上通过我的本地网络进行测试,如果有任何帮助的话。提前谢谢......

1 个答案:

答案 0 :(得分:1)

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

    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()