Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending a socket.io .once message

This would work without the .once call.

I am trying to send a single message from server side code with

io.on('connect', function (socket) { socket.once('connect', function() { socket.emit('mydata', { feed: result});

but I get nothing on the client side unless I remove the second line. I also tried socket.once('mydata', { feed: result}) but:

throw new TypeError('listener must be a function');

In other words how can one send a message to the client side only when there is new 'mydata'?

Thanks

like image 670
staminna Avatar asked Dec 28 '25 13:12

staminna


1 Answers

First off, .once() is for event listeners only - when you only want to be notified of the next time an event occurs, not subsequent times it occurs. It has nothing to do with sending messages.

What your specific code is trying to do doesn't really make sense. You're in a connect event and you're trying to listen for another connect event? It would help if you described more completely what you're trying to accomplish? What does "only when there is a new mydata mean"? How does one tell if there's a new mydata?

If you're just trying to send the mydata message, when the client first connects, you can just do this:

io.on('connect', function(socket) {
    socket.emit('mydata', { feed: result });
}

If you're trying to make sure you only send this message once to the connection even in case of a reconnect on the same socket, you can do this:

io.on('connect', function(socket) {
    if (!socket.sentMydata) {
        socket.emit('mydata', { feed: result });
        socket.sentMydata = true;
    }
}

If you want to make sure this client is ever only sent this message once, even if the page is reloaded or the client navigated away and back, then you will have to use a persistent marker like a cookie or some session id or something like that.

like image 58
jfriend00 Avatar answered Jan 01 '26 16:01

jfriend00