让我们考虑一个示例后端设置;大多数重要的注释都在一行中:
# 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 之前的字符存在。
© 版权声明
本站下载的源码均来自公开网络收集转发二次开发而来,
若侵犯了您的合法权益,请来信通知我们1413333033@qq.com,
我们会及时删除,给您带来的不便,我们深表歉意。
下载用户仅供学习交流,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担,访问及下载者下载默认同意本站声明的免责申明,请合理使用切勿商用。
THE END
暂无评论内容