javascript 同一页面上的多个 socket.io 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15901688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple socket.io connections on the same page
提问by arunkjn
Can I connect to multiple resources on the same IP and port on the client side?
我可以连接到客户端相同 IP 和端口上的多个资源吗?
I have the following code-
我有以下代码-
var myIP = "192.168.1.1";
var myPort = "8080";
A = io.connect(myIP+':'+myPort,{resource: 'A/socket.io'});
B = io.connect(myIP+':'+myPort,{resource: 'B/socket.io'});
A.on('connect',console.log('A connected');
B.on('connect',console.log('B connected');
A.on('message',function(d){console.log('A: '+ d);}
B.on('message',function(d){console.log('B: '+ d);}
I am running node-http-proxyon myIP:myPort
.
It is proxying connections on A and B to their respective socket-io servers.
我运行节点的HTTP代理上myIP:myPort
。它将 A 和 B 上的连接代理到它们各自的 socket-io 服务器。
If I run the above code on a single script, the browser ignores the second statement (It does not fires a request to resource B).
如果我在单个脚本上运行上述代码,浏览器将忽略第二条语句(它不会向资源 B 发出请求)。
The on(message)
callbacks for both A and B recieve the same data which actually belongs to A.
on(message)
A 和 B的回调收到实际上属于 A 的相同数据。
If I run the above code in two different html pages (A on one and B on other), they work fine and I get the data for both separately.
如果我在两个不同的 html 页面(一个页面上的 A 和另一个页面上的 B)中运行上面的代码,它们工作正常并且我分别获取了两个页面的数据。
采纳答案by maxdec
Try this:
试试这个:
A = io.connect(myIP+':'+myPort, {resource: 'A/socket.io', 'force new connection': true});
B = io.connect(myIP+':'+myPort, {resource: 'B/socket.io', 'force new connection': true});
(Yes, I removed some of the quotes)
(是的,我删除了一些引号)
回答by RandallB
I would also mention Namespaces... a lot of times what you're trying to do is handle reconnect events on a per socket basis, namespaces do this for you. Their major upside is you don't need to have a connection per each one, which means they don't contribute to the 6-connections-per-domain limit of browsers.
我还要提到命名空间......很多时候你试图做的是在每个套接字的基础上处理重新连接事件,命名空间为你做这件事。它们的主要优点是您不需要每个连接都有一个连接,这意味着它们不会影响浏览器的每个域 6 个连接的限制。
To connect, simply do this:
要连接,只需执行以下操作:
socket = io('/namespace')
socket = io('/namespace')