在python中使用socket时应该如何正确配置任务?

问题描述 投票:0回答:1

我有这个小片段,我打算将其用作服务器,我已设法让套接字连接到客户端,但由于错误而无法发送数据。

import asyncio
import json
import socketio
from aiohttp import web

ALLOWED_ORIGINS = ["http://localhost:45100"]

sio = socketio.AsyncServer(cors_allowed_origins=ALLOWED_ORIGINS)
app = web.Application()#socketio.ASGIApp(sio)
sio.attach(app)

@sio.event
async def connect(sid, environ):
    origin=environ.get('HTTP_ORIGIN', '')
    if origin not in ALLOWED_ORIGINS:
        print(f'Connection from {origin} imetupwa')
        await sio.disconnect(sid)

    else:
        print(f'Allowing connection from {origin}')

@sio.event
async def disconnect(sid):
    print('Disconnected', sid)

async def send_gpio_data():
    print('Going to send data')
    try:
        while True:
            data = {'speed': 100}
            await sio.emit('ecuData', json.dumps(data))
            print("Data sent, sleeping...")
            await asyncio.sleep(1)
    except Exception as error:
        print(f'Error in sending data: {error}')

async def main():
    print('Init main')
    asyncio.create_task(send_gpio_data())

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, '0.0.0.0', 8090)
    print("Web app running on http://0.0.0.0:8090")
    await site.start()

    await asyncio.Event().wait()


if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Done!")

这是输出:

Init main
Web app running on http://0.0.0.0:8090
Going to send data
Data sent, sleeping...
Allowing connection from http://localhost:45100
Error in sending data: Passing coroutines is forbidden, use tasks explicitly.
/Users/keronei/StudioProjects/Side Projects/rotor/server.py:35: RuntimeWarning: coroutine 'AsyncServer._emit_internal' was never awaited
  print(f'Error in sending data: {error}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

崩溃后执行立即停止,我也尝试过

 sio.start_background_task(send_gpio_data)
但我得到了同样的错误。

python coroutine python-socketio
1个回答
0
投票
import asyncio
import json
import socketio
from aiohttp import web

ALLOWED_ORIGINS = ["http://localhost:45100"]

sio = socketio.AsyncServer(cors_allowed_origins=ALLOWED_ORIGINS)
app = web.Application()
sio.attach(app)

@sio.event
async def connect(sid, environ):
    origin = environ.get('HTTP_ORIGIN', '')
    if origin not in ALLOWED_ORIGINS:
        print(f'Connection from {origin} rejected')
        await sio.disconnect(sid)
    else:
        print(f'Allowing connection from {origin}')

@sio.event
async def disconnect(sid):
    print('Disconnected', sid)

async def send_gpio_data():
    print('Going to send data')
    try:
        while True:
            data = {'speed': 100}
            await sio.emit('ecuData', data)  # No need to json.dumps, just send dict
            print("Data sent, sleeping...")
            await asyncio.sleep(1)
    except Exception as error:
        print(f'Error in sending data: {error}')

async def main():
    print('Init main')
    # Schedule the coroutine to run in the background
    sio.start_background_task(send_gpio_data)

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, '0.0.0.0', 8090)
    print("Web app running on http://0.0.0.0:8090")
    await site.start()

    await asyncio.Event().wait()

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("Done!")
© www.soinside.com 2019 - 2024. All rights reserved.