简体   繁体   中英

Changing server from client-side on Socket.io

This is my first question on this website. A lot of my questions on Google have been answered thanks to this site, but I can't find an answer to my question, or I just can't think of the right way to post the question.

I have three Socket.IO servers that should change by clicking different buttons. What I thought is this: var pot_bot = io('12.12.12.12:3222'); pot_bot.on('action', function(data) { console.log('unique data '+data.hi);}); if(button1.clicked) pot_bot = io('12.12.12.12:3223'); var pot_bot = io('12.12.12.12:3222'); pot_bot.on('action', function(data) { console.log('unique data '+data.hi);}); if(button1.clicked) pot_bot = io('12.12.12.12:3223');

Everything is correct, the problem is that when I override the variable pot_bot I would like the .on('action') to be called when the new server emits it. This isn't the case with the code example from above.

Does anyone have a solution for this?

I would suggest removing the event listener from the old manager before overwriting pot_bot and then binding a new listener to the new one. (io caches the managers so if you every switch back you get the old manager back, and if you keep adding the listener, without ever removing them, you will get duplicate listeners on the same manager). You can put it all in a function so that you don't have to repeat code:

function switch_to_server( new_uri ) {
    pot_bot && pot_bot.removeListener( 'action' );

    pot_bot = io( new_uri);
    pot_bot.on('action', function(data) { console.log('unique data '+data.hi);});
}

if ( button1.clicked )
    switch_to_server( '12.12.12.12:3223' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM