I am using socket io and express. i want to broadcast my message to all users of room but insted of users of that room all users who are connected recive message. Room id is room id
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 8080;
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
app.use(cors({origin: true}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
io.on('connection', async (socket) => {
console.log('user connected');
}
Now This is message block
socket.on('message' , async (data)=>{
//want to broadcast message to all users except sender
//Room is Group1Room and room id is RoomId
io.emit('message', {message:"hello" , socketId:socket.id})
//recive message
io.on('message' , (data)=>{
console.log('data is ' data);
})
}
```ata,{ where: { id } });
CodePudding user response:
socket.emit is used to emit an event globally.All user connected to socket will will listen and get data. for sharing a message in room use
socket.broadcast.to(roomid).emit()
your code will be like that
socket.broadcast.to(event).emit( 'message' , {message:message,
socketId:socket.id
});