Is it possible to global emit only to sender but outside the socket.on('connect') event? I'm looking for something like socket.broadcast.to().emit() which I can use in app.post method, which is not in connect method, so I can't use just socket.emit
app.post('/room', function(req, res) {
io.sockets.emit('something');
});
'something' I want to emit only to SENDER
My code:
socket_id;
app.post('/room', function(req, res) {
if (req.body.user == ''){
io.sockets.socket(socket_id).emit('usernameError', 'Type your username');
}
else if (users[req.body.user] !== undefined ) {
io.sockets.socket(socket_id).emit('usernameError', 'Username exists.');
}
else{
users[req.body.user] = req.body.user;
user = req.body.user;
io.sockets.emit('newUser', user+' join to the room');
res.render('room');
}
});
io.sockets.on('connection', function(socket) {
socket.username = user;
socket.join('room1');
socket.id = socket_id;
});
As far as I understand you want to send "something" to the user that just came to /room page, right?
If so, you can't do it in app.post method because this code will execute before the client will receive the HTML code,
and thus handshake between client and server will not be established.
I think the best solution would be executing the following code on the client side on /room page only:
var socket = io.connect('/'); //your socket.io connection (may be different)
socket.on('something', function(data) {
console.log(data);
});
socket.emit('i_am_room_page'); //tell server we are on /room page
And on the server:
io.sockets.on('connection', function(socket) {
socket.on('i_am_room_page', function(data) {
socket.emit('something', {your: 'data'});
});
});
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With