Can someone help to solve problem with server to capture and send video over TCP/IP from usb camera connected to Raspberry pi 4b to laptop

Here i have a example of server.py code on python for Raspberry pi to capture video from usb camera “A4 Tech” connected to Raspberry pi 4b

import cv2
import socket
import struct
import pickle
import logging

logging.basicConfig(level=logging.DEBUG)

def send_frame(client_socket, frame):
    # Serialize the frame using pickle
    data = pickle.dumps(frame)
    # Pack the size of the serialized frame
    message_size = struct.pack("Q", len(data))
    try:
        # Send the size of the serialized frame to the client
        client_socket.sendall(message_size)
        # Send the serialized frame data to the client
        client_socket.sendall(data)
        logging.debug(f"Sent frame size: {len(data)} bytes.")
        return True
    except Exception as e:
        logging.error(f"Error sending data: {e}")
        return False

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = 'IP'  # Use the Raspberry Pi's IP address
port = 8000
server_socket.bind((host, port))
server_socket.listen(5)

camera = cv2.VideoCapture(0, cv2.CAP_V4L2)  # Use V4L2 backend explicitly
if not camera.isOpened():
    logging.error("Failed to open camera")
    exit()

camera.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)

logging.info('Waiting for client connection...')

try:
    while True:
        client_socket, addr = server_socket.accept()
        logging.info(f'Connected to {addr}')
        if client_socket:
            try:
                while camera.isOpened():
                    ret, frame = camera.read()
                    if not ret:
                        logging.error("Failed to read frame from camera")
                        break
                    if not send_frame(client_socket, frame):
                        break
            except Exception as e:
                logging.error(f"Error during frame send loop: {e}")
            finally:
                client_socket.close()
except KeyboardInterrupt:
    logging.info("Server stopping")
finally:
    camera.release()
    server_socket.close()

And here is client.py code to recieve video but it doesnt work

import cv2
import socket
import struct
import pickle
import logging

logging.basicConfig(level=logging.DEBUG)

def receive_frame(client_socket):
    data = b""
    payload_size = struct.calcsize("Q")
    
    # Receive the size of the incoming frame
    while len(data) < payload_size:
        packet = client_socket.recv(4096)
        if not packet:
            logging.error("No payload received. Exiting.")
            return None
        data += packet
    
    if len(data) < payload_size:
        logging.error(f"Incomplete payload size received. Expected size: {payload_size}, received size: {len(data)}. Exiting.")
        return None

    packed_msg_size = data[:payload_size]
    data = data[payload_size:]
    msg_size = struct.unpack("Q", packed_msg_size)[0]
    logging.debug(f"Expected message size: {msg_size} bytes.")

    # Receive the actual frame data
    while len(data) < msg_size:
        packet = client_socket.recv(4096)
        if not packet:
            logging.error(f"Incomplete data received. Expected size: {msg_size}, received size: {len(data)}. Exiting.")
            return None
        data += packet

    if len(data) != msg_size:
        logging.error(f"Data received does not match expected size. Expected: {msg_size}, Got: {len(data)}")
        return None

    try:
        frame_data = pickle.loads(data)
        return frame_data
    except pickle.UnpicklingError as e:
        logging.error(f"Error deserializing data: {e}")
        return None
    
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'Same IP'  # Use the Raspberry Pi's IP address
port = 8000
client_socket.connect((host, port))

try:
    while True:
        frame = receive_frame(client_socket)
        if frame is None:
            logging.error("No data packet received")
            break
        cv2.imshow('Video', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
except Exception as e:
    logging.error(f"Error processing data: {e}")
finally:
    client_socket.close()
    cv2.destroyAllWindows()

Server.py debug “DEBUG:root:Sent frame size: 230564 bytes.” and error in client.py “DEBUG:root:Expected message size: 230564 bytes.
ERROR:root:Data received does not match expected size. Expected: 230564, Got: 231572
ERROR:root:No data packet received”
Maybe someone know how to fix this problem and make this code work

i have ensure the server dynamically calculates and sends the frame size with each frame. This was done by serializing the frame data, packing the size, and sending both the size and data to the client. But it didnt work

New contributor

Nickvels is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật