You recently needed to emulate the server in your project: The server continuously sends images and their strings to the client, which receives the information, processes it, and sends the results back to the server.

On the Internet to find a lot of socket code, or can only send string information does not support picture transmission; Either the client sends the image to the server, because the general logic is to start the server first and then start the client, so it is also strange to simply change the body of the image to the server, because then only the client can start first.

Finally, I chose the second one. After completion, I was not very willing to start the client before starting the server, which made me feel awkward. [realization].

Not willing to, after a lot of hard work, finally found Python WebSocket method (before only know Java WebSocket), the code is simpler than Socket, and allows the server to send data to the client, is suitable for my needs. This code can only transmit simple strings, but I’m happy to change it.

WebSocket is a protocol for full-duplex communication over a single TCP connection. WebSocket makes it easy to exchange data between the client and the server,
Allows the server to actively push data to the client.

Socket is a low-level interface that can only transmit data in the format of bytes. WebSocket, however, is an application layer protocol that can transfer data in other formats (actually parsing into Bytes at the bottom level), such as JSON. However, I also need to transfer the string as well as the image. If I use JSON, I can either package it into a dictionary and convert it to JSON, or send two JSONs, which would be very confusing. It’s better to just send two Bytes.

Numpy images and strings are converted to Bytes streams in the same way as in the previous article.


server.py

import asyncio import websockets import cv2 async def echo(websocket, path): Video_path = 'D:/test/ CCC /mp4/1.mp4' # cap = CV2.videoCapture (video_path) # read video FPS = cap.get(CV2.cap_prop_fps) # While True: k=0 while cap.isopened (): success, frame = cap.read() if success: k += 1 if k % (FPS *4) == 0: Img_encode = cv2.imencode('.jpg', img_encode = cv2.imencode('.jpg'), img_encode = cv2.imencode('.jpg'), Frame) img_data = img_encode.tobytes() # Construct string string tobytes Img_name = (STR (k)+'.jpg'). Encode () # Send Message Aawait Send (img_data) await websocket.send(img_name) print(' have successfully sent %3d.jpg, sleep 1 second '%k) await asyncio.sleep(1) # sleep 1 second cap.release() if __name__ == '__main__': Start_server = websockets. Serve (echo,'127.0.0.1',6666) # Change your own address asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()

client.py

import asyncio import websockets import numpy as np import cv2 import os async def hello(uri): async with websockets.connect(uri) as websocket: os.makedirs('./save',exist_ok=True) while True: Img_data = await websocket.recv() # await message img_name = await websocket.recv() # Convert image bytecode bytes to a one-dimensional Numpy array in the cache Img_Buffer_NumPy = np.fromBuffer (img_data, dtype=np.uint8) # Read 1D NumPy data from the specified memory cache, Frame = cv2.imdecode(img_buffer_numpy, 1) name = img_name.decode() cv2.imwrite('./save/'+name, Frame) print (' has been successfully received, name) if __name__ = = "__main__ ': Asyncio.get_event_loop ().run_until_complete(hello('ws://127.0.0.1:6666')) # Change your own address

If you run server.py first, then client.py, the effect is: