SoFunction
Updated on 2024-10-29

python uses socket to efficiently transfer video data frames (sending pictures continuously)

Problems encountered

I've looked for some code on the internet, but I can only establish a socket once to transfer an image, and then disconnect and reconnect to re-transmit it. The cost of setting up a socket once is not small, and setting it up again and again would beIt consumes a lot of system resources, so try transferring multiple images at once through a socket by yourself!

Code problem logging (if you need the code, you can just go to the end of the article)

Found a few problems in the process of doing it:

The socket transmits an image as a binary stream. The binary stream of an image is relatively large, and it is usually not finished at one time, but has to be transmitted many times. So how does the receiver know when to stop receiving this picture? Well, you can have the sender send a header message before sending the picture, telling the receiver how long the binary stream is, and then the receiver can use this to determine if it's finished.

This problem is the most fatal to me, since the sender first sends a header message, using the () function, and then sends the picture also to use the () function, and the receiver is using the (1024) function, and the (1024) is cached large. Trouble comes, since the sender uses two consecutive sends, and (1024) is cached, he will cache the two messages together, the message header and the picture message are all cached!!!! This will directly cause the code to receive the logic incorrectly. The way I do it is that there can't be two sends at the same time, so I add a recv function (a blocking function) in the middle of the send, which means that for every message the sender sends, the receiver immediately replies with a message, which ensures that there are no consecutive sends!

在这里插入图片描述 

coding

Since there are two data sources for the project, one visible and one infrared, I had to create a message header in the beginning to tell the receiver what type of data this is every time I send it and then receive it

It's not easy to make, so remember to give a shout out!

client (computing)

# Address of the server
server_address = ('127.0.0.1', 8000)


def send(dir_name, data_format, file_name):
    # Establish socket communication with the receiver
    sock = (socket.AF_INET, socket.SOCK_STREAM)  # AF_INET (TCP/IP - IPv4) Protocol
    (server_address)

    # Each communication carries a communication header indicating the type of data source (infrared or visible), the name of the folder where the data frames are to be stored file_name
    # You don't want the data format, here you can define it in your own form, it's kind of a security mechanism #
    ('{}|{}'.format(data_format, file_name).encode())  # Default encoding utf-8, send file length and file name
    reply = (1024)

    # Sorted by file name,,, #
    file_list = (dir_name)
    file_list.sort(key=lambda x: int(x[:-4]))
    if 'ok' == ():  # Confirm that the server gets the file length and filename data.
        i = 0
        print(len(file_list))
        for file_name in file_list:
            data = file_deal((dir_name, file_name))
            ('{}|{}'.format(len(data), file_name).encode())
            (1024)
            go = 0
            total = len(data)
            while go < total:  # Send files
                data_to_send = data[go:go + total//2]
                (data_to_send)
                go += len(data_to_send)
            (1024).decode()
            i += 1
            if i < len(file_list):
                (b'continue')
        (b'over')
        ()
        (0)


def file_deal(file_path):  # The way to read a file
    mes = b''
    try:
        file = open(file_path, 'rb')
        mes = ()
    except:
        print('error{}'.format(file_path))
    else:
        ()
        return mes

server-side

LOCAL_IP = '127.0.0.1'  # Local test ip, LAN use need to change ip
PORT = 8000  # Specify a port at random

def server():
    sock = (socket.AF_INET, socket.SOCK_STREAM)  # socket.AF_INET refers to the ipv4 socket.SOCK_STREAM using the tcp protocol.
    (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # Set the port
    ((LOCAL_IP, PORT))  # Bind ports
    (3)  # Listening to ports
    while True:
        sc, sc_name = ()  # When a request is made to the specified port accept() returns a new socket and the (ip,port) of the other host.
        print('received{}machine request'.format(sc_name))
        info = (1024)  # Accept protocol headers from the client to distinguish between data sources
        # Security Handling: If it doesn't start with this protocol header, it is considered illegal access and is simply disconnected. Here you can define some security message mechanism yourself
        print(info)
        try:
            data_format, directory_name = ().split("|")
            (b'ok')  # Indicates the length and name of the file received
        except:
            print('Wrong protocol header, auto disconnect')
            ()
            continue

        if not (directory_name):
            (directory_name)
        # Continuously receive incoming data frames once the protocol header is correct.
        while True:
            head_info = (1024)
            # print(data_info)
            length, file_name = head_info.decode().split('|')
            (b'ok')
            if length and file_name:
                print(file_name)
                newfile = open((directory_name, file_name), 'wb')  # Here you can use the filename parsed from the client
                file = b''
                total = int(length)
                get = 0
                while get < total:  # Receive documents
                    data = (total//2)
                    file += data
                    get = get + len(data)
                (b'ok')
                print('It should be accepted.{},Actual intake{}'.format(length, len(file)))
                if file:
                    print('actually length:{}'.format(len(file)))
                    (file[:])
                    ()
            reply = (1024)
            if () == "over":
                break

server()

priming step

1. Start first
2. Reboot

reference article

/hfutzhouyonghang/article/details/86624684

to this article on the use of python socket efficient transmission of video data frames (continuous sending pictures) of the article is introduced to this, more related python socket transmission of video data frames content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!