-
-
Notifications
You must be signed in to change notification settings - Fork 103
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
添加 ws 和 webhook 集成 #405
Comments
安装依赖pip install "python-socketio[asyncio]" 创建一个 sio
from socketio import AsyncServer
def create_socketio(
cors_allowed_origins: str | list = '*',
async_mode: str = 'asgi',
**kwargs
) -> AsyncServer:
return AsyncServer(
cors_credentials=True,
async_mode=async_mode,
cors_allowed_origins=cors_allowed_origins,
**kwargs
)
sio = create_socketio()
@sio.event
async def connect(sid, environ, auth):
print(f'connected auth={auth} sid={sid}')
await sio.emit('hello', ({'hello': 'you'}), to=sid) 设置一个 socketio 的路由
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socketio
import uvicorn
from backend.core.registrar import register_app
from backend.core.socketio import sio
fastapi_app = register_app()
combined_asgi_app = socketio.ASGIApp(socketio_server=sio, other_asgi_app=fastapi_app)
fastapi_app.add_route('/socket.io/', route=combined_asgi_app, methods=['GET', 'POST'])
fastapi_app.add_websocket_route('/socket.io/', combined_asgi_app)
if __name__ == '__main__':
try:
uvicorn.run(combined_asgi_app, host='127.0.0.1', port=8000, reload=True, log_level='info')
except Exception as e:
raise e vue 前端连接 socketiopnpm add socket.io-client
import { io } from 'socket.io-client'
onMounted(() => {
const socket = io('http://127.0.0.1:8000', {
autoConnect: true, // 是否自动连接
path: '/socket.io',
reconnection: true, // 是否自动重新连接
reconnectionAttempts: 3, // 重新连接尝试次数
reconnectionDelay: 1000, // 重新连接延迟时间(ms)
transports: ['websocket'], // 指定传输方式,如WebSocket
})
socket.on('hello', (message) => {
console.log(message) // {hello: 'you'}
})
}) |
@elkon028 非常感谢您提供帮助 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
related: #210 #212 #328
The text was updated successfully, but these errors were encountered: