pyropy / fastapi-socketio

Easily integrate socket.io with your FastAPI app 🚀
Apache License 2.0
328 stars 31 forks source link

this is not even working at all #22

Closed ahmetkca closed 2 years ago

ahmetkca commented 3 years ago

main.py

from fastapi import FastAPI
from fastapi_socketio import SocketManager

app = FastAPI()
socket_manager = SocketManager(app=app)

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

@app.sio.on('connect')
async def handle_connect(sid, *args, **kwargs):
    await app.sio.emit('connect', 'User joined')

CLIENT SIDE


import {io} from 'socket.io-client';

const socket =  io('ws://127.0.0.1:8000', {
      path: 'ws/socket.io',
      autoConnect: true
  })

  socket.on('connect', (data) => {
    console.log(data)
  })``` 
jpez16 commented 2 years ago

check your ports, are you using docker?

jujaryu commented 2 years ago

you have typo in path string, change

path: 'ws/socket.io' to path: '/ws/socket.io'

dustinmichels commented 2 years ago

Setting path to '/ws/socket.io seems to have worked for me...

I would really appreciate a little more documentation on how to connect to the server!

cande1gut commented 2 years ago

Whoever ends up here and is trying within a python client, you can establish a connection with:

import socketio

sio = socketio.Client()

@sio.on('connect_server')
def connected(message):
    print(message)

sio.connect('http://{ip}{port}/ws', socketio_path="/ws/socket.io", wait_timeout = 10)
sio.wait()
ahmetkca commented 2 years ago

I ended up using socketio itself;

MySocketManager.py

class MySocketManager:
    def __init__(self, app: FastAPI) -> None:
        self._mgr = socketio.AsyncRedisManager(REDIS_TLS_URL)
        self._sio: AsyncServer = socketio.AsyncServer(
            client_manager=self._mgr, 
            async_mode=ASYNC_MODE, 
            cors_allowed_origins=[]
        )
        self._app = socketio.ASGIApp(
            socketio_server=self._sio,
            socketio_path=SOCKETIO_PATH
        )
        app.mount(MOUNT_LOCATION, self._app)
        app.sio = self._sio
        logging.info

    def get_socket_manager(self) -> AsyncServer:
        return self._sio

app.py

from MySocketManager import MySocketManager as SocketManager

app = FastAPI()
socketio_manager = SocketManager(app)
sm: AsyncServer = socketio_manager.get_socket_manager()
connected_users = set()

@sm.on('connect')
async def on_connect(sid, *args, **kwargs):
    print('a user connected ', sid)

@sm.on('disconnect')
async def on_disconnect(sid, *args, **kwargs):
    sm.leave_room(sid, room='orderaio')
    ss = await sm.get_session(sid)
    connected_users.remove(ss['username'])
    print('a user disconnected ', sid)

and make sure when you establish a connection from client use "/ws/socket.io/" as your path.