server端:
# ftp server端 import socket, os, time server = socket.socket() server.bind(("localhost", 8080)) server.listen() while True: conn, addr = server.accept() print("连接到客户端:", addr) while True: try: # windows会直接报错,需要捕获异常 data = conn.recv(1024) if not data: print("客户端已断开") break except Exception as e: print("客户端已经断开") break cmd, filename = data.decode().split() # ex: get name.txt if os.path.isfile(filename): f = open(filename, "rb") # 获取文件的字节大小 size = os.stat(filename).st_size conn.send(str(size).encode()) # 发送文件大小 conn.recv(1024) for line in f: # 客户端确认后发送文件内容 conn.send(line) f.close() print("文件下载完成") conn.send("not file".encode()) server.close()
client端:
import socket client = socket.socket() client.connect(("localhost", 8080)) while True: cmd = input(">>:").strip() if len(cmd)==0: continue if cmd.startswith("get"): client.send(cmd.encode()) # 发送请求 server_response = client.recv(1024) if server_response.decode().startswith("not"): print("请输入有效文件名") continue client.send(b"ready to recv file") # 发送确认 file_size = int(server_response.decode()) # 获取文件大小 rece_size=0 filename = cmd.split()[1] f = open(filename + ".new", "wb") while rece_size < file_size: if file_size - rece_size > 1024: # 要收不止一次 size = 1024 else: # 最后一次了,剩多少收多少,防止之后发送数据粘包 size = file_size - rece_size print("last receive:", size) recv_data = client.recv(size) rece_size += len(recv_data) # 累加接受数据大小 f.write(recv_data) # 写入文件,即下载 else: print("文件下载完成") f.close() client.close()
测试案例:
主要是socket的简单使用,主要节点都有注释
原文地址:https://www.cnblogs.com/houzheng/p/10292889.html
时间: 2024-10-16 00:54:10