Search code examples
socket.iohapi

HapiJS and Socket IO not emit


I'm trying to setup socket.io with hapi. I've setup a barebones repo here: https://github.com/imcodingideas/socketio-hapi-example but this is the gist of it. On the server.js I am listening for a connection

  io.sockets.on('connection', (socket) => {
    socket.emit({ msg: 'welcome' })
  })

and on the client I'm sending a connection

socket.on('msg', data => {
  console.log(data)
  socket.emit('my other event', { my: 'data' })
})

I'm not getting any cors errors or nothing so it's able to connect.


Solution

  • Your code does work and it doesn't matter where you put the server.start().

    The problem is your client side code. The event socket.on('connection') does not exist for the socket.io client. The event is called connect.

    IO - Event: ‘connect’ Documentation

    The following code snippet should work.

    const socket = io('http://localhost:8081');
    
    socket.on('connect', data => {
        console.log('connected');
    });
    
    socket.on('msg', data => {
        console.log(data);
    });
    
    setTimeout(() => {
        socket.emit('another event', 'another events data')
    }, 2000)
    

    server:

    const init = async () => {
      const io = SocketIO.listen(server.listener)
    
      io.sockets.on('connection', (socket) => {
        socket.emit('msg', 'welcome')
    
        socket.on('another event', (data) => {
          console.log(data);
        })
      })
    
      await server.start()
      console.log(`Server running at: ${server.info.uri}`)
    }