Python TCP通信之仿文件下载

TCP_文件下载_Client.py
import socket


def main():
    # 创建TCP套接字
    tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 链接服务器
    tcp_socket.connect(("127.0.0.1", 5001))
    # 获取下载的文件的名字
    download_file_name = input("请输入要下载的文件名字:")
    # 将文件名字发送到服务器
    tcp_socket.send(download_file_name.encode("utf-8"))
    # 接收文件中的数据
    recv_data = tcp_socket.recv(1024)
    if recv_data:
        # 保存接收到的数据到一个新的文件中
        with open("[新]" + download_file_name, "wb") as f:
            f.write(recv_data)
    # 关闭套接字
    tcp_socket.close()


if __name__ == '__main__':
    main()
TCP_文件下载_Server.py
import socket


def main():
    # 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定本地信息
    tcp_server_socket.bind(("", 5001))
    # 监听
    tcp_server_socket.listen(128)
    while True:
        # 等待客户端的链接
        new_client_socket, client_addr = tcp_server_socket.accept()
        file_name = new_client_socket.recv(1024).decode("utf-8")
        print("客户端(%s)需要下载的文件名字是:%s" % (str(client_addr), file_name))
        file_content = None
        try:
            f = open(file_name, "rb")
            file_content = f.read()
            f.close()
        except Exception as result:
            print("没有要下载的文件%s" % file_name)
        if file_content:
            new_client_socket.send(file_content)
        # 关闭套接字
        new_client_socket.close()
    tcp_server_socket.close()


if __name__ == '__main__':
    main()

 

 
 
posted @ 2019-08-11 20:27  李道臣  阅读(317)  评论(0编辑  收藏  举报