要通过UDP发送图像(或其他大文件),你需要将文件分割成多个较小的数据包,然后通过UDP协议逐个发送
socket
库来创建UDP套接字。确保你已经安装了Python。以下是一个简单的示例,展示了如何通过UDP发送图像:
发送端(sender.py):
import socket
import os
def send_file(file_path, host, port):
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65536)
# 打开文件并读取内容
with open(file_path, 'rb') as f:
file_data = f.read()
# 分割文件为数据包
packet_size = 1024
for i in range(0, len(file_data), packet_size):
packet = file_data[i:i + packet_size]
seq_num = i // packet_size
packet_with_seq = f"{seq_num}:{packet.decode('latin1')}"
sock.sendto(packet_with_seq.encode('latin1'), (host, port))
print("File sent successfully!")
if __name__ == "__main__":
file_path = "path/to/your/image.jpg"
host = "127.0.0.1"
port = 12345
send_file(file_path, host, port)
接收端(receiver.py):
import socket
import os
def receive_file(host, port, output_file):
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536)
received_packets = {}
expected_seq_num = 0
while True:
data, addr = sock.recvfrom(65536)
seq_num_str, packet_data = data.decode('latin1').split(':', 1)
seq_num = int(seq_num_str)
if seq_num == expected_seq_num:
received_packets[seq_num] = packet_data.encode('latin1')
expected_seq_num += 1
# 如果接收到所有数据包,重新组装文件
if expected_seq_num * 1024 >= os.path.getsize(output_file):
with open(output_file, 'wb') as f:
for i in range(expected_seq_num):
f.write(received_packets[i])
print("File received successfully!")
break
else:
received_packets[seq_num] = packet_data.encode('latin1')
if __name__ == "__main__":
host = "127.0.0.1"
port = 12345
output_file = "received_image.jpg"
receive_file(host, port, output_file)
领取专属 10元无门槛券
手把手带您无忧上云