最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple socket.io connections on the same page - Stack Overflow

programmeradmin4浏览0评论

Can I connect to multiple resources on the same IP and port on the client side?

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-proxy on myIP:myPort. It is proxying connections on A and B to their respective socket-io servers.

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).

The on(message) callbacks for both A and B recieve the same data which actually belongs to 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.

Can I connect to multiple resources on the same IP and port on the client side?

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-proxy on myIP:myPort. It is proxying connections on A and B to their respective socket-io servers.

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).

The on(message) callbacks for both A and B recieve the same data which actually belongs to 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.

Share Improve this question edited Oct 17, 2013 at 8:54 arunkjn asked Apr 9, 2013 at 12:18 arunkjnarunkjn 5,9315 gold badges23 silver badges31 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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)

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.

To connect, simply do this:

socket = io('/namespace')

发布评论

评论列表(0)

  1. 暂无评论