io.on('connection', (socket) => {
var ip = socket.client.request.headers['x-forwarded-for'] || socket.client.conn.remoteAddress || socket.conn.remoteAddress || socket.request.connection.remoteAddress;
console.log(ip)
console.log('user ket noi ' clients)
clients
//io.emit("new msg", { msg: `Hiện tại có ${clients} đang kết nối !!` });
io.broadcast.emit("new msg", { msg: `Hiện tại có ${clients} đang kết nối !!` });
socket.on('on-chat', data => {
io.emit('user-chat', data)
})
})
file index.js , i can't use io.broadcast.emit but i can use io.emit how can i fix pls ;( i'm newbie
error in cmd
C:\Users\Admin\Documents\heroku\Chat-real-time\index.js:34
io.broadcast.emit("new msg", { msg: Hiện tại có ${clients} đang kết nối !!
});
^
TypeError: Cannot read property 'emit' of undefined at Namespace. (C:\Users\Admin\Documents\heroku\Chat-real-time\index.js:34:15) at Namespace.emit (events.js:400:28) at Namespace.emitReserved (C:\Users\Admin\Documents\heroku\Chat-real-time\node_modules\socket.io\dist\typed-events.js:56:22) at C:\Users\Admin\Documents\heroku\Chat-real-time\node_modules\socket.io\dist\namespace.js:141:26 at processTicksAndRejections (internal/process/task_queues.js:77:11) [nodemon] app crashed - waiting for file changes before starting...
CodePudding user response:
To broadcast you need to call it from the socket instance not the io instance. So it would be:
socket.broadcast.emit()
You can read more about emitting events in the socket.io docs