从客户端接收字节后生成文件

时间:2016-11-26 19:52:34

标签: python sockets

我想做一个简单的文件传输程序,将文件从客户端传输到服务器。服务器向客户端发送路径,客户端将文件发送到服务器。但我不知道如何在服务器部分创建文件。实际上,我以二进制模式发送所有文件,但之后我收到服务器模式中的每个字节,我不知道如何从我收到的字节中生成文件。

客户端部件

sock = 0
path = " "


def open_socket():
    global sock
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("localhost", 9000))


def transfer_file(path):
    f = open(path, "rb").read()
    sock.send(f)


def main():
    open_socket()
    path = sock.recv(1024)



if __name__ == "__main__":
    main()

服务器部件

def open_connection():
    global client
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("0.0.0.0", 9000))
    sock.listen(1)
    client, address = sock.accept()


def file_transfer():
    path = raw_input("Enter path of file: ")
    client.send(path)
    while True:
        file_from_client = client.recv(1024)


def main():
    open_connection()
    file_transfer()



if __name__ == "__main__":
    main()

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要在套接字上多做一些工作,包括使用let lines = contents.components(separatedBy: "\n") for line in lines { let words = line.components(separatedBy: " ") print("\(words[0]) is \(words[1]) and likes \(words[4])") } 而不是sendall(可能发送的内容少于完整缓冲区)并找出一种方法让读者知道数据何时有完成发送。由于您没有可以让您请求多个文件的消息边界,我的示例关闭了套接字,让另一方知道传输已完成。我也摆脱了全局变量。这将传输一个文件:

<强> client.py

send

<强> server.py

import socket

def open_socket():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("localhost", 9000))
    return sock

def transfer_file(sock, path):
    f = open(path, "rb").read()
    sock.sendall(f)

def main():
    sock = open_socket()
    path = sock.recv(1024)
    transfer_file(sock, path)
    sock.shutdown(socket.SHUT_RDWR)
    sock.close()

if __name__ == "__main__":
    main()