socket通信代码

import time
import asyncio
import socketio


class Sio:
    def __init__(self):
        print('Initializing Sio class instance...')
        self.sio = socketio.AsyncClient()
        self.host = host
        self.path = '/bridge-socket/autotest-chat'
        self.result = None

        self.sio.on('connect', self.on_connect)
        self.sio.on('disconnect', self.on_disconnect)
        self.sio.on('handle_result', self.on_js_result)

        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.start())

    async def start(self):
        try:
            print(f'Attempting connection to {self.host}')
            await self.sio.connect(self.host, socketio_path=self.path)
            print('Connection successful')
        except Exception as e:
            print(f'Failed to connect: {e}')

    async def on_connect(self):
        print('Connected to Socket.IO server')

    async def on_disconnect(self):
        print('Disconnected from Socket.IO server')

    async def on_js_result(self, data):
        print('Received JS execution result:', data)
        self.result = data

    async def send_execute_js(self, bridgeInfo):
        print(f'Sending execute_js with bridgeInfo: {bridgeInfo}')
        await self.sio.emit('execute_js', {'execId': self.execute_id, "bridgeInfo": bridgeInfo})

    async def invokeJsFuction(self, bridgeInfo):
        print(f'Invoking JS Function with bridgeInfo: {bridgeInfo}')
        await self.send_execute_js(bridgeInfo)
        start_time = time.time()
        timeout = 10  # Timeout after 10 seconds
        while self.result is None:
            if time.time() - start_time > timeout:
                print('Timeout waiting for JS execution result')
                return None
            await asyncio.sleep(0.1)
        result = self.result
        self.result = None  # 重置结果
        print(f'Invoke result: {result}')
        return result

# 示例调用
try:
    sio_instance = Sio()
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(sio_instance.invokeJsFuction(params)
except Exception as ex:
    print(f'An error occurred: {ex}')

问题定位:

Failed to connect: Unexpected status code 400 in server response

原因:
1、证书问题导致:pip install --upgrade certifi
2、engineio和socketio版本冲突,指定版本安装:

        python-engineio==4.9.1
        python-socketio==5.11.3
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值