发送者: send_file.py
def send_file(filename: str = "mytext.txt", testing: bool = False) -> None:
import socket
port = 12312
sock = socket.socket()
host = socket.gethostname()
sock.bind((host, port))
sock.listen(5)
print("Server listening....")
while True:
conn, addr = sock.accept()
print(f"Got connection from {addr}")
data = conn.recv(1024)
print(f"Server received: {data }")
with open(filename, "rb") as in_file:
data = in_file.read(1024)
while data:
conn.send(data)
print(f"Sent {data!r}")
data = in_file.read(1024)
print("Done sending")
conn.close()
if testing:
break
sock.shutdown(1)
sock.close()
if __name__ == "__main__":
send_file()
启动python文件: 出现: servering listening
received_file.py
if __name__ == "__main__":
import socket
sock = socket.socket()
host = socket.gethostname()
port = 12312
sock.connect((host, port))
sock.send(b"Hello server!")
with open("Received_file", "wb") as out_file:
print("File opened")
print("Receiving data...")
while True:
data = sock.recv(1024)
print(f"{data }")
if not data:
break
out_file.write(data)
print("Successfully got the file")
sock.close()
print("Connection closed")
接收者这边也启动received_file:
另外同时send_file也收到: 文件结构如下: 参考:
import socket
import os
import hashlib
server = socket.socket()
server.bind(("localhost", 6969))
server.listen(5)
print("监听开始..")
while True:
conn, addr = server.accept()
print("conn:", conn, "\naddr:", addr)
while True:
data = conn.recv(1024)
if not data:
print("客户端断开连接")
break
print("收到的命令:", data.decode("utf-8"))
cmd, filename = data.decode("utf-8").split(" ")
if cmd =="get":
if os.path.isfile(filename):
size = os.stat(filename).st_size
conn.send(str(size).encode("utf-8"))
print("发送的大小:", size)
conn.recv(1024)
m = hashlib.md5()
f = open(filename, "rb")
for line in f:
conn.send(line)
m.update(line)
f.close()
md5 = m.hexdigest()
conn.send(md5.encode("utf-8"))
print("md5:", md5)
server.close()
Python编程:socket实现文件传输
import socket
import os
import hashlib
client = socket.socket()
ip_port =("localhost", 6969)
client.connect(ip_port)
print("服务器已连接")
while True:
content = input(">>")
if len(content)==0: continue
if content.startswith("get"):
client.send(content.encode("utf-8"))
server_response = client.recv(1024)
file_size = int(server_response.decode("utf-8"))
print("接收到的大小:", file_size)
client.send("准备好接收".encode("utf-8"))
filename = "new" + content.split(" ")[1]
f = open(filename, "wb")
received_size = 0
m = hashlib.md5()
while received_size < file_size:
size = 0
if file_size - received_size > 1024:
size = 1024
else:
size = file_size - received_size
data = client.recv(size)
data_len = len(data)
received_size += data_len
print("已接收:", int(received_size/file_size*100), "%")
m.update(data)
f.write(data)
f.close()
print("实际接收的大小:", received_size)
md5_sever = client.recv(1024).decode("utf-8")
md5_client = m.hexdigest()
print("服务器发来的md5:", md5_sever)
print("接收文件的md5:", md5_client)
if md5_sever == md5_client:
print("MD5值校验成功")
else:
print("MD5值校验失败")
client.close()
|