python实现客户端和服务端的UDP相互通信
实验指南
这篇博客旨在实验客户端和服务端相互发送消息的实验,实验成功的现象为,客户端和服务端的两个窗口,即client和server左上角均被打上文字,因为客户端是没有给图片附上文字的功能的,十分感谢柒上夏OPO大佬提供源码上的支持
客户端代码
import numpy as np
import cv2
from socket import socket, AF_INET, SOCK_DGRAM
# 127.0.0.1表示本机的IP,用于测试,使用时需要改为服务端的ip
addr = ("127.0.0.1", 8081)
IP_ADDR = ("127.0.0.1", 8082)
cap = cv2.VideoCapture(0)
# 设置镜头分辨率,默认是640x480
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
s = socket(AF_INET, SOCK_DGRAM) # 创建UDP套接字
s.bind(IP_ADDR)
while True:
_, img = cap.read()
img = cv2.flip(img, 1)
# 压缩图片
_, send_data = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 50])
s.sendto(send_data, addr)
print(f"正在发送数据,大小:{img.size} Byte")
# cv2.putText(img, "client", (50, 50),
# cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
# cv2.imshow("client", img)
try:
data, _ = s.recvfrom(921600)
print("info: ", _)
receive_data = np.frombuffer(data, dtype="uint8")
r_img = cv2.imdecode(receive_data, 1)
cv2.imshow("client", r_img)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
except BlockingIOError as e:
pass
if cv2.waitKey(1) & 0xFF == ord("q"):
break
s.close()
cv2.destroyAllWindows()
服务端代码
from copy import deepcopy
import numpy as np
import cv2
from socket import socket, AF_INET, SOCK_DGRAM
s = socket(AF_INET, SOCK_DGRAM) # 创建UDP套接字
addr = ("0.0.0.0", 8081) # 0.0.0.0表示本机
s.bind(addr)
s.setblocking(0) # 设置为非阻塞模式
while True:
data = None
try:
data, s_addr = s.recvfrom(921600)
print("[IP_INFO] {}".format(s_addr))
receive_data = np.frombuffer(data, dtype="uint8")
r_img = cv2.imdecode(receive_data, 1)
r_img_1 = deepcopy(r_img)
r_img_2 = deepcopy(r_img)
cv2.putText(r_img_1, "server", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.imshow("server", r_img_1)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.putText(r_img_2, "client", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
_, send_data = cv2.imencode(
".jpg", r_img_2, [cv2.IMWRITE_JPEG_QUALITY, 50])
s.sendto(send_data, s_addr)
print(f"正在发送数据,大小:{r_img.size} Byte")
except BlockingIOError as e:
pass
cv2.destroyAllWindows()
实验历程
假设服务端代码放在server.py的文件中,先打开一个终端
python server.py
假设客户端代码放在client.py的文件中,再打开一个终端,输入
python client.py
实验成功的现象
客户端和服务端的两个窗口,即client和server左上角分别被打上client和server的字样,因为客户端是没有给图片附上文字的功能的