SurajitCh
SurajitCh

Reputation: 33

cannot read property 'emit' of undefined socketio

I'm building a project using socket.io. while running getting the error "TypeError: Cannot read property 'emit' of undefined".

server code is given below:

server.js

const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')

app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/', (req, res) => {
  res.redirect(`/${uuidV4()}`)
})

app.get('/:room', (req, res) => {
  res.render('room', { roomId: req.params.room })
})

io.on('connection', socket => {
  socket.on('join-room', (roomId, userId) => {
    socket.join(roomId)
    socket.to(roomId).broadcast.emit('user-connected', userId)

    socket.on('disconnect', () => {
      socket.to(roomId).broadcast.emit('user-disconnected', userId)
    })
  })
})

server.listen(3000)

Can anyone help to rectify the error?

Upvotes: 3

Views: 2819

Answers (2)

Tahir77667
Tahir77667

Reputation: 2512

  • If you're getting this error, I'm assuming you are following this video tutorial How To Create A Video Chat App With WebRTC
  • In this tutorial Kyle is using socket.io version 2.0.3
  • You are facing issues since you might be using socket version '4.0.1'. Apparently in this version, the broadcast property is no longer available/has been removed which is why you are getting the above TypeError.
  • Also call the 'to()' method on the io object instead of the socket object.

Solution:

Replace this:

socket.to(roomId).broadcast.emit('user-connected', userId)

With this:

io.to(roomId).emit('user-connected', userId);

For further information, please refer this documentation: Socket.io rooms

Upvotes: 0

kuntervert
kuntervert

Reputation: 106

It seems that your socket function is written in the wrong order

Try this:

socket.broadcast.to(roomId).emit('user-connected', userId)

and this:

  socket.broadcast.to(roomId).emit('user-disconnected', userId)

Upvotes: 2

Related Questions