1.服務端
import socket, os
server = socket.socket()
server.bind(('0.0.0.0', 22222))
server.listen()
while True:
conn, addr = server.accept()
print("new conn:", addr)
while True:
data = conn.recv(1024)
if not data:
print("客戶端已斷開")
break
cmd, filename = data.decode().split()
if os.path.isfile(filename):
# 獲取檔案大小
file_zise = os.stat(filename).st_size
conn.send(str(file_zise).encode("utf-8"))
f = open(filename, "rb")
conn.recv(1024)
for line in f:
m.update(line)
conn.send(line)
f.close()
server.close()
2.客戶端
import socket
client = socket.socket()
client.connect(('localhost', 22222))
while True:
cmd = input(">>:").strip()
if len(cmd) == 0: continue
if cmd.startswith("get"):
client.send(cmd.encode("utf-8"))
server_respons = client.recv(1024)
client.send("知道接收的檔案大小了".encode("utf-8"))
file_total_size = int(server_respons.decode())
received_size = 0
filename = cmd.split()[1]
f = open(filename + ".new", "wb")
while received_size < file_total_size:
data = client.recv(1024)
received_size += len(data)
f.write(data)
else:
print("file recv done")
f.close()
client.close()