让我们考虑一个示例后端设置;大多数重要的注释都在一行中

让我们考虑一个示例后端设置;大多数重要的注释都在一行中:

# projectroot/backend/app.py
import socketio
from fastapi import FastAPI
# Explicitly defined for easy comparison to frontend; normally use a .env file for this
SOCKETIO_MOUNTPOINT = "/bar"  # MUST START WITH A FORWARD SLASH

SOCKETIO_PATH = "foo"
# While some tutorials use "*" as the cors_allowed_origins value, this is not safe practice.
CLIENT_URLS = ["http://localhost:3000", "ws://localhost:3000"]
# Define the socket serverIO and application
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=CLIENT_URLS)
sio_app = socketio.ASGIApp(socketio_server=sio, socketio_path=SOCKETIO_PATH)

# Define the main fastapi application
app = FastAPI()
# Must mount the socketio application to a mountpoint in other to use socketio paths
# other then the default "socket.io"
app.mount(SOCKETIO_MOUNTPOINT, sio_app)

@sio.event
async def connect(sid, environ, auth):
    print(f"Connected to frontend with socket ID: {sid}")
    await sio.emit("message", f"Backend has connected to using socket ID: {sid}")

@sio.event
def disconnect(sid):
    print(f"Socket with ID {sid} has disconnected")
@sio.event

async def message(_, msg):
    print(f"Recieved the following message from the frontend: {msg}")
    await sio.emit("response", f"Responding from backend. Original message was: {msg}")

通常,如果您当前的工作目录是project_root,您将在终端中激活您的python 环境并使用uvicorn backend.app:app 启动后端。

这是前端的实现:

所以,问题的关键在于,在客户端的SocketIO配置中,在定义socket/manager/etc时,path属性必须要加入挂载点和socketio路径。

请注意,当不涉及挂载时(即只是一个 python socketio 服务器),仍然有一个挂载点。因此,公式仍将保留为 mountpoint/socketiopath,正斜杠仍作为 socketiopath 之前的字符存在。

© 版权声明
THE END
喜欢就支持一下吧
点赞270 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片