简体   繁体   English

在Socket.io上从客户端更改服务器

[英]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. 感谢这个网站,我在Google上的许多问题都得到了解答,但是我找不到问题的答案,或者我只是想不出正确的方式来发布问题。

I have three Socket.IO servers that should change by clicking different buttons. 我有三个Socket.IO服务器,应通过单击不同的按钮进行更改。 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'); 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. 一切都正确,问题是当我覆盖变量pot_bot时,我希望在新服务器发出它时调用.on('action')。 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. 我建议在覆盖pot_bot之前从旧的管理器中删除事件侦听器,然后将新的侦听器绑定到新的侦听器。 (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). (io会缓存管理器,因此,如果您每次切换回去,您都将恢复原来的管理器,并且如果继续添加侦听器而从未删除它们,则您将在同一管理器上获得重复的侦听器)。 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' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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