How to fix Socket.io with nitro server in NuxtJS 3?

312 views Asked by At

I'm trying to use socket.io with the NuxtJS 3 nitro server. The problem is that my websocket only works in development mode. When I send it to production I cannot receive a response from the websocket.

Maybe it's because I'm not using the same port as my http server. How can I solve the problem?

module/socket.ts:

import { Server } from 'socket.io'
import { defineNuxtModule } from '@nuxt/kit'

const clients: any = {};

export default defineNuxtModule({
  setup(options, nuxt) {
    nuxt.hook('listen', (server) => {
      console.log('Socket listen', server.address(), server.eventNames())
      const io = new Server(server)

      nuxt.hook('close', () => io.close())

       io.on('connection', (socket) => {
         console.log('new connection', socket.id)
         clients[socket.id] = socket.handshake.query.clientId;
       })


      io.on('connect', (socket) => {

        socket.on('message', function message(data: any) {
          console.log('message received: %s', data)

          const customId = Object.keys(clients).find(key => clients[key] === data['id']);
          if (customId) {
            console.log('sending to', customId)
            socket.to(customId).emit('widget', data)
          }
        })

        socket.on('disconnecting', () => {
          console.log('disconnected', socket.id)
          delete clients[socket.id];
        })
      });
    })
  },
})
0

There are 0 answers