Skip to content

Dear project team, I have encountered some problems #1226

@RavenCri

Description

@RavenCri

It seems like a bug. Why can't messages be sent immediately in asynchronous mode? After checking the class log, the emit has been executed, and the message was delayed for a long time before it was actually sent. The client only received the message. Below, how can I provide asynchronous mode to send messages immediately? Can you give me some help

Server:

import asyncio
import time
from threading import Thread

import socketio
from aiohttp import web

from loguru import logger

clients = []

def connect(sid, environ):
    logger.info(f"connect, sid={sid}")
    clients.append(sid)


def disconnect(sid):
    logger.info(f"{sid}断开")
    clients.remove(sid)

def cour(func):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(func())
def response(sid, msg):
    logger.info(f"receive:{msg}")


async def send_msg():
    while True:
        if len(clients) > 0:
            await sio.emit(event='send_msg', to=clients[0], data="hello")
            logger.info("send to client msg=> hello")
        time.sleep(5)


sio = socketio.AsyncServer(async_mode='aiohttp', logger=False)

if __name__ == '__main__':
    sio.on('connect', connect)
    sio.on('disconnect', disconnect)
    sio.on('response', response)
    app = web.Application()
    sio.attach(app)
    Thread(target=cour, args=(send_msg,)).start()
    web.run_app(app, host='localhost', port=8080, )

Client:

import asyncio

import socketio
from loguru import logger

sio = socketio.AsyncClient()

async def receive_msg(msg):
    logger.info(f"receive: {msg}")
    await sio.emit('response', 'ok!')
async def run_client():
    sio.on('send_msg', receive_msg)
    await sio.connect('http://localhost:8080')

    await sio.wait()

if __name__ == '__main__':
    asyncio.run(run_client())

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions