wobsoriano / nuxt3-socket.io

Nuxt 3 and Socket.io integration.
59 stars 9 forks source link

Can not access globalThis.__io #12

Open duytnb79 opened 10 months ago

duytnb79 commented 10 months ago

When I access globalThis.__io, it always return undefined. How can I fix it ? Thank you for supporting.

Additional, I use environment io.to(roomId).emit('function') to send message to specific room in socket. I think we need to guide to use it.

duytnb79 commented 10 months ago

Sorry for not clearly, I mean I want to use globalThis.__io in development environment. But I see this code in file server.ts

export function createIOHandler<T extends Record<string, (io: SocketServer) => void>> (functions: T, serverOptions: Partial<ServerOptions>) {
  return eventHandler((event) => {
    if (!globalThis.__io && process.env.NODE_ENV === 'production') {
      const httpServer = (event.node.req.socket as any).server as Server
      const io = new SocketServer(httpServer, serverOptions)

      Object.keys(functions).forEach((fn) => {
        functions[fn](io)
      })

      globalThis.__io = io
    }
  })
}

Can you point me how to use it.

felixrydberg commented 9 months ago

I found this aswell. I have no clue why its only set to run this code while in production and not in development

ivan-skjavik commented 8 months ago

Is it possible to access the socket from middlewares so that it can be attached to the context?

felixrydberg commented 8 months ago

You would have to set your .env.NODE_ENV = 'production'

However. Nitro seems to have issues with websockets, it doesnt allow new connections after 6 clients has connected even if some of them disconnect. I would recommend following this thread as it seems like Nitro is working on websockets support. https://github.com/unjs/nitro/issues/678