Python-Socket编程实现tcp-udp通信

时间:2024-05-02 08:30:32

本文章是记录我准备大创项目时学的socket编程的用法,纯属记录生活,没有教学意义,视频我是看b站up主王铭东学的,讲的很详细,我只粗略学了个大概,我想要通过tcp,udp传输yolo目标检测中的物体坐标信息给单片机,然后小车实现追踪(只是初步想法),有更好的办法的话,欢迎讨论~

UDP传输视频客户端:

import socket
import cv2

# 服务器地址和端口
SERVER_IP = '192.168.0.101'
SERVER_PORT = 7890

# 创建UDP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 打开摄像头
cap = cv2.VideoCapture(0)

# 检查摄像头是否成功打开
if not cap.isOpened():
    print("Error: Failed to open camera.")
    exit()

# 设置数据包大小
PACKET_SIZE = 65507

while True:
    # 从摄像头读取一帧视频
    ret, frame = cap.read()

    # 检查是否成功读取到帧
    if not ret:
        print("Error: Failed to read frame from camera.")
        break

    # 编码视频帧数据
    _, frame_data = cv2.imencode('.jpg', frame)
    frame_data = frame_data.tobytes()

    # 分割帧数据并发送给服务器
    total_size = len(frame_data)
    num_packets = total_size // PACKET_SIZE + 1

    for i in range(num_packets):
        start = i * PACKET_SIZE
        end = min((i + 1) * PACKET_SIZE, total_size)
        client_socket.sendto(frame_data[start:end], (SERVER_IP, SERVER_PORT))

    # 显示帧
    cv2.imshow('Client', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 关闭摄像头、窗口和套接字
cap.release()
cv2.destroyAllWindows()
client_socket.close()

UDP服务端:

import socket
import cv2
import numpy as np
# 服务器地址和端口
SERVER_IP = '192.168.0.101'
SERVER_PORT = 7890

# 创建UDP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((SERVER_IP, SERVER_PORT))

# 设置数据包大小
PACKET_SIZE = 65507

while True:
    # 接收来自客户端的帧数据
    frame_data, _ = server_socket.recvfrom(PACKET_SIZE)

    # 检查接收到的帧数据是否为空
    if not frame_data:
        print("Error: Received empty frame data.")
        continue

    # 解码帧数据
    nparr = np.frombuffer(frame_data, np.uint8)
    frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    # 检查解码是否成功
    if frame is None:
        print("Error: Failed to decode frame.")
        continue

    # 显示帧
    cv2.imshow('Server', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 关闭窗口和套接字
cv2.destroyAllWindows()
server_socket.close()

如果要用的话也很容易,最起码得安装opencv和socket相关包,然后查看服务端的ip地址,插上摄像头,就可以开始传输视频了。效果如图所受:

                                                            如果有问题,欢迎交流