日常生活的交流与学习

首页 新随笔 联系 管理

代码逻辑图

image

E:\song\下载的文件\fastapi-socketio-example-master\backend\asgi.py

import uvicorn
from api import config, app


if __name__ == '__main__':
    uvicorn.run('asgi:app', host=config.HOST, port=config.PORT, reload=True)

E:\song\下载的文件\fastapi-socketio-example-master\backend\config.py

import os

LOCALHOST = '127.0.0.1'


class BaseConfig:

    def __init__(self, host=LOCALHOST, port=5000):
        self.HOST = host
        self.PORT = port

E:\song\下载的文件\fastapi-socketio-example-master\backend\api\__init__.py

from fastapi import FastAPI
from config import BaseConfig


config = BaseConfig()

app = FastAPI(title='TeamChat clone')

from . import routes
from . import sockets
app.mount('/ws', sockets.sio_app)

E:\song\下载的文件\fastapi-socketio-example-master\backend\api\routes\hello_world.py

from fastapi import APIRouter


router = APIRouter()

@router.get('/hello')
async def hello():
    return {'hello': 'world'}

@router.get('/ping')
async def ping():
    return {'ping': 'pong'}

E:\song\下载的文件\fastapi-socketio-example-master\backend\api\routes\__init__.py

from api import app
from . import hello_world


app.include_router(hello_world.router, tags=['Test Route'], prefix='/hello_world')

E:\song\下载的文件\fastapi-socketio-example-master\backend\api\sockets\index.py

from . import sio


# Temporary data
current_active_users = []

@sio.event
def connect(sid, environ):
    print(f"{sid } is connected.")

@sio.on('message')
async def broadcast(sid, data: object):
    print(f'sender-{sid}: ', data)
    await sio.emit('response', data)

@sio.on('update_status')
async def broadcast_status(sid, data: object):
    print(f'status {data["presence"]}')
    data['sid'] = sid

    if data not in current_active_users:
        current_active_users.append(data)
    
    if data['presence'] == 'offline':
        for user in current_active_users:
            if user['name'] == data['name']:
                current_active_users.remove(user)

    await sio.emit('status', current_active_users)

@sio.event
async def disconnect(sid):
    print('disconnected from front end', sid)
    for user in current_active_users:
        if user['sid'] == sid:
            user['presence'] = 'offline'
    print(current_active_users)
    await sio.emit('re_evaluate_status')


E:\song\下载的文件\fastapi-socketio-example-master\backend\api\sockets\__init__.py

import socketio

sio = socketio.AsyncServer(
    async_mode='asgi',
    cors_allowed_origins='*'
)
sio_app = socketio.ASGIApp(sio)

from . import index
posted on 2023-01-12 19:23  lazycookie  阅读(261)  评论(0编辑  收藏  举报