# UDP传输字符串
import socket
import time


tx_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tx_socket.bind(("192.168.233.65", 7070))
rx_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx_socket.bind(("192.168.233.65", 9090))

start_time = time.time()
tx_socket.sendto("Jiahong is cool!"
.encode("utf-8"), ("192.168.233.65", 9090))
rec = rx_socket.recvfrom(65536)[0].decode("utf-8")
stop_time = time.time()
print((stop_time-start_time)*1000)
tx_socket.close()
rx_socket.close()
# UDP传输图像
import socket
import time
import PIL.Image as Image
import numpy as np
from timeit import timeit


src_img = Image.open('UDP.jpg')
src_img.convert('RGB')
src_img = src_img.resize((224, 224))
R = list(src_img.getdata(band=0))
G = list(src_img.getdata(band=1))
B = list(src_img.getdata(band=2))
all_pixels = R+G+B
bytes_array = bytes(all_pixels)
# UDP报文分片
bytes_array1 = bytes_array[:len(bytes_array)//3]
bytes_array2 = bytes_array[len(bytes_array)//3:len(bytes_array)//3*2]
bytes_array3 = bytes_array[len(bytes_array)//3*2:]

tx_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tx_socket.bind(("192.168.233.65", 7070))
rx_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx_socket.bind(("192.168.233.65", 9090))

start_time = time.time()

flag = 0
rec1 = []
rec2 = []
rec3 = []
current_time = time.time()
while True:
if time.time() - current_time >= 0.0001: # 模拟发送端定时发送和接收端异步接收
if flag == 0:
tx_socket.sendto(bytes_array1, ("192.168.233.65", 9090))
rec1 = list(rx_socket.recvfrom(65536)[0])
flag = 1
elif flag == 1:
tx_socket.sendto(bytes_array2, ("192.168.233.65", 9090))
rec2 = list(rx_socket.recvfrom(65536)[0])
flag = 2
else:
tx_socket.sendto(bytes_array3, ("192.168.233.65", 9090))
rec3 = list(rx_socket.recvfrom(65536)[0])
break
current_time = time.time()

stop_time = time.time()
print((stop_time - start_time) * 1000)

tx_socket.close()
rx_socket.close()

rec = rec1+rec2+rec3
R = rec[:len(rec)//3]
G = rec[len(rec)//3:len(rec)//3*2]
B = rec[len(rec)//3*2:]

pic = np.zeros((224, 224, 3))
channel_count = 0
for hh in range(224):
for ll in range(224):
pic[hh][ll][0] = R[channel_count]
pic[hh][ll][1] = G[channel_count]
pic[hh][ll][2] = B[channel_count]
channel_count += 1
pic = pic.astype(np.uint8)
pil_image = Image.fromarray(pic)

pil_image.show()