【问题标题】:Socket.io-client on node.js works only oncenode.js 上的 Socket.io-client 只工作一次
【发布时间】:2012-10-14 12:00:37
【问题描述】:

每当服务器收到请求时,我想在服务器端(使用 node.js)创建新的 sockei.io-client。但是下面的代码只工作一次,然后 sockei.io-client 没有响应。应用程序不会停止,没有错误。

var http = require("http");


http.createServer(function(request, response) {

var io = require('socket.io-client'); 
localSocket = io.connect('http://localhost:9876/');
localSocket.on('connect', function (data) {
                         response.writeHead(200, {"Content-type": "text/plain"});
                         response.write(data.name);
                         response.end();
                         localSocket.disconnect();
       });


}).listen(8080);

Socket.io 服务器(在 localhost:9876 上)运行良好 - 它为具有名称的客户端提供服务(即

 data.name

在此处的代码中)。

怎么了?

更新:问题自己解决了:要为socket.io-client运行多个连接需要添加连接选项{'force new connection': true},像这样:

localSocket = io.connect('http://localhost:9876/', {'force new connection': true});

谢谢!

【问题讨论】:

  • 感谢您更新了答案。我建议不要更新,而是将其添加为答案
  • force new connection 已从 socket.io 1.0 更改为 forceNew

标签: node.js socket.io


【解决方案1】:

对于那些在谷歌上找到这个的人 - 现在有一个解决方案:

Socket.disconnect() 踢客户端(服务器端)。客户没有机会保持联系:)

force client disconnect from server with socket.io and nodejs

我认为您只需删除 disconnect() 行。

【讨论】:

  • 好吧,我知道 disconnect() 做了什么。每次收到 http 请求时,我都想创建新的 socket.io-client 并连接到服务器。
猜你喜欢
  • 2012-04-26
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多