0

I am trying to build an real-time chat app using socket io. I am also new and learning socket io. I am getting this error:

    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: sent 1000 (OK); no close frame received
INFO:     connection closed
ERROR:    Exception in ASGI app

don't understand why the connection is being closed. here is my fast api code:

sio = socketio.AsyncServer(cors_allowed_origins="*")
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# Mount the static files directory
chat_namespace = "/chat"

@sio.event(namespace=chat_namespace)
async def connect(sid, environ):
    print('Connected:', sid)

@sio.event(namespace=chat_namespace)
async def join_room(sid, data):
    room = data['room']
    await sio.enter_room(sid, room, namespace=chat_namespace)
    print('User joined room:', room)

@sio.event(namespace=chat_namespace)
async def leave_room(sid, data):
    room = data['room']
    await sio.leave_room(sid, room, namespace=chat_namespace)
    print('User left room:', room)

@sio.event(namespace=chat_namespace)
async def message(sid, data):
    room = list(await sio.rooms(sid, namespace=chat_namespace))[1]  # Use [1] to get the second room (index 0 is the default room)
    await sio.emit('message', data, room=room, skip_sid=sid, namespace=chat_namespace)
    print('Message:', data, 'in room:', room)

@sio.event(namespace=chat_namespace)
async def disconnect(sid):
    print('Disconnected:', sid)

sio_app = socketio.ASGIApp(sio, static_files={"/static": "static"})

app.mount("/socket.io", sio_app)

@app.get("/mysc")
async def read_root():
    return {"Hello": "Socket.IO"}

here is my react code:

  useEffect(() => {
        const currentUserID = 'A'; // User A's ID
        const recipientUserID = 'B'; // User B's ID
    
        const roomName = generateRoomName(currentUserID, recipientUserID);
    
        const socket = io('http://localhost:8000/mysc', { path: '/socket.io', transports: ['websocket'] });
    
        // Join the room corresponding to the private conversation
        socket.emit('join_room', { room: roomName });
    
        // Send a private message
        socket.emit('message', { text: 'Hello, user B!' });
    
        // Listen for messages
        socket.on('message', (message) => {
          console.log('Received private message:', message);
        });
    
        // Clean up the WebSocket connection on component unmount
        return () => {
          socket.disconnect();
        };
      }, []);
    
      // Function to generate the room name
      const generateRoomName = (user1, user2) => {
        // Sort the user IDs to ensure consistent room naming
        const sortedIDs = [user1, user2].sort();
        return `${sortedIDs[0]}-${sortedIDs[1]}`;
      };

my react server running on localhost:3000 and fast api running on loaclhost:8000

boyenec
  • 1,405
  • 5
  • 29

0 Answers0