环境

windows 11
python 3.11
fastapi 0.108.0
fastapi-socketio 0.0.10
vue2
“socket.io-client”: “^4.6.1”,
提示:如果遇到跨域问题自行解决

fastapi

使用fastapi-scoketio下的SocketManager, 可以看到接口解释如下:

fastapi_socketio连接vue的socktio.client-LMLPHP
所以默认配置是客户端连接时使用的路径时ws,而不是http, 并且路径还要带上socketio.io

服务端
from fastapi import FastAPI
from fastapi_socketio import SocketManager

app = FastAPI()

# 重点,使用默认配置
socket_manager = SocketManager(app=app)

@app.get("/")
async def index():
    return {"message": "Hello World"}

@socket_manager.on("connect")
async def connect(sid, environ):
    print(f"Client {sid} connected")

@socket_manager.on("message")
async def message(sid, data):
    print(f"Received message from {sid}: {data}")
    await socket_manager.emit("response", {"data": "Message received"}, room=sid)

@socket_manager.on("disconnect")
async def disconnect(sid):
    print(f"Client {sid} disconnected")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

vue

mounted() {
    this.socket = io('ws://127.0.0.1:8000', {
        transports: ['websocket'],
        path: '/ws/socket.io'
      });
     
    this.socket.on('connect', () => {
      console.log('Connected to server');
    });
    this.socket.on('response', (data) => {
      console.log('Received response:', data);
    });
  },
  methods: {
    sendMessage() {
      console.log('Sending message');
      this.socket.emit('message', { data: 'Hello from Vue' });
    },
  },
11-08 07:56