使用FastApi和Reaction实现Socketio [英] Socketio implementation with FastApi and React

查看:0
本文介绍了使用FastApi和Reaction实现Socketio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下技术堆栈

  1. FastApi-后端
  2. 反应-前端

并希望实现Socketio(而不是FastApi提供的WebSockets)。它缺少FastApi和Socketio的文档

推荐答案

根据需要,我们使用python-socketio作为后端套接字服务器,在Reaction上我们将使用socket.io-client。 安装后,我们需要设置套接字服务器。

后端实现

# socket.py

def handle_connect(sid, environ):
    logger.info(f"Socket connected with sid {sid}")

class SocketManager:
    def __init__(self, origins: List[str]):
        self.server = socketio.AsyncServer(
            cors_allowed_origins=origins,
            async_mode="asgi",
            logger=True,
            engineio_logger=True,
        )
        self.app = socketio.ASGIApp(self.server)

    @property
    def on(self):
        return self.server.on

    @property
    def send(self):
        return self.server.send

    def mount_to(self, path: str, app: ASGIApp):
        app.mount(path, self.app)


socket_manager = SocketManager(settings.origins)
socket_manager.on("connect", handler=handle_connect)

仔细检查您的CORS来源。您还可以使用socket_manager.on添加其他处理程序。

#main.py

from socket import 

app = FastAPI(...)
socket_manager.mount_to("/ws", app)

前台实施 集成的基本代码就像

一样简单
import { io } from "socket.io-client";

const socket = io("ws://localhost:8000", {{ path: "/ws/socket.io/", transports: ['websocket', 'polling'] }});
socket.on("connect", () => { console.log("Connected", socket.id) }); 
socket.on("response", () => { console.log("Response", socket.id) });  
socket.on("message", data => { console.log(data) });

我为我的项目创建了一个上下文,如下所示

import React, { createContext, useContext, useEffect, useState } from 'react';

import { io } from "socket.io-client";
import { useToastContext } from './ToastContext';


export const SocketContext = createContext()


export const SocketProvider = ({ children, uri, options }) => {
    const [socketIo, setSocketIo] = useState()
    const { sendToast } = useToastContext();

    useEffect(() => {
        const socket = io(uri, options);
        socket.on("connect", () => { console.log("Connected", socket.id) });
        socket.on("response", () => { console.log("Response", socket.id) });
        socket.on("message", data => { 
            sendToast(data)
        });
        setSocketIo(socket)
    }, [])

    return (
        <SocketContext.Provider value={socketIo}>
            {children}
        </SocketContext.Provider>
    )
}

export const useSocket = () => {
    return useContext(SocketContext)
}

现在,要最终将邮件从服务器发送到客户端,您可以执行以下操作

socket_manager.send("Hello World")

注意事项

    CORS来源应完全相同如果是来自前端的http://localhost:3000,则应该是http://localhost:3000,而不是http://localhost:3000/.查找反斜杠
  • Socketio文档还说transports: ['websocket', 'polling']是默认的,但当我删除它时。它给了我CORS错误。文档可能已过时。

这篇关于使用FastApi和Reaction实现Socketio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆