Websocket Links Python has many wrapped libraries: Websocket-client, WebSockets, aiowebsocket, websokets

2. WSS protocol 3. Serialization and deserialization of both sending and receiving data (Probuff)

# encoding = utf-8
import asyncio
import pathlib
import ssl
import websockets
import base64
from pb import conn_ready_pb2
import uuid
import datetime,time
import json
from google.protobuf import json_format
The server declares CLIENT_AUTH
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
CLIENT_AUTH This value indicates that the context can be used for authenticating Web clients (thus, it will be used to create server-side sockets), carfile server certificates
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile="D://my_project//Ajcloud//ca.crt")
The # certFile and keyfile parameters specify an optional file that contains the certificate used to identify the connection on the local side, the client side certificate
ssl_context.load_cert_chain(certfile="D://my_project//Ajcloud//mgr.crt", keyfile="D://my_project//Ajcloud//mgr.key")
ssl_context.verify_mode = ssl.CERT_REQUIRED

async def hello():
    uri = "wss://xxxxxxxxxx"
    async with websockets.connect(
            uri, ssl=ssl_context
    ) as websocket:
        message = "xxxxx"
        reg = conn_ready_pb2.ConnReadyRequest()
        res = conn_ready_pb2.ConnReadyResponse()
        reg.header.message_id = str(uuid.uuid1())
        datetime_now = datetime.datetime.now()
        date_stamp = str(int(time.mktime(datetime_now.timetuple())))
        data_microsecond = str("%06d" % datetime_now.microsecond)[0:3]
        date_stamp = date_stamp + data_microsecond
        reg.header.message_ts = date_stamp
        r = reg.SerializeToString()# serialization
        b = base64.b64encode(r)  Convert binary to Base64 encoding
        b2 = str(b, 'utf-8')
        message = {"xxx": "xxx"."yyyy": b2}
        await websocket.send(json.dumps(message))
        print(f"> {message}")
        greeting = await websocket.recv()
        payload = json.loads(greeting)["payload"]
        # base64 transcodes to binary
        payload =base64.b64decode(payload)
        res.ParseFromString(payload)# deserialize
        json_result = json_format.MessageToJson(res)  # pb convert to JSON format
        print(json_result)
        print(f"< {greeting}")


asyncio.get_event_loop().run_until_complete(hello())

Copy the code