下载文件要保证文件的完整性, 一般采用TCP协议进行两台主机间的socket通信
1 client.py
from socket import *
tcp_socket = socket(AF_INET, SOCK_STREAM)
dest_ip = input("请输入下载服务器的ip:")
dest_port = int(input("请输入服务器的port:"))
tcp_socket.connect((dest_ip, dest_port))
down_file = input("请输入下载的文件名字:")
tcp_socket.send(down_file.encode("utf-8"))
recv_data = tcp_socket.recv(1024)
if recv_data:
with open("[新]"+down_file, "wb") as f:
f.write(recv_data)
tcp_socket.close()
2 server.py
from socket import *
def send_file_to_client(client_socket, client_addr):
# 接收客户端需要下载的文件名
file_name = client_socket.recv(1024).decode("utf-8")
print("客户端 {} 要下载的文件是:{}".format(client_addr, file_name))
# 打开这个文件,读取数据
file_content = None
try:
f = open(file_name, "rb") # 以二进制读取
file_content = f.read()
f.close()
except Exception as ret:
print("没有要下载的文件:{}".format(file_name))
# 发送文件数据到客户端
if file_content:
client_socket.send(file_content)
tcp_socket = socket(AF_INET, SOCK_STREAM)
print("服务器绑定端口号:7890")
tcp_socket.bind(("", 7890))
print("令tcp_socket变为监听套接字")
tcp_socket.listen()
print("正在等待接收客户端的连接请求...")
client_socket, client_addr = tcp_socket.accept()
print("客户端信息:", client_addr)
send_file_to_client(client_socket, client_addr)
client_socket.close()
tcp_socket.close()