Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

【新人】socket.io自动建立很多连接的问题

直接上代码吧,服务器端:

var express=require('express');
var app=express();
var net=require('net');
var http=require('http').createServer(app);
var io=require('socket.io').listen(http);
var net=require('net');
var nodeServer = new net.Socket();
var aSocket=null;

io.sockets.on('connection', function (socketIO) {
  aSocket=socketIO;
};
nodeServer.on('data', function(data) {
 if(aSocket!=null){
    aSocket.emit('pushToWebClient',useData);
    //客户端断开连接
    aSocket.on('disconnect', function () {
      console.log('DISCONNECTED FROM CLIENT');
    });

  }

客户端:

socket.on('pushToWebClient', function (useData) {

        
    });
    

代码截取了部分,过程是:从一个C++写的服务器接受数据,socket.io转发数据给客户端,然后显示到页面上。
接受一会,如果关闭网页,就会出现一堆

DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
DISCONNECTED FROM CLIENT
...(此处省略无数行)

我估计是每次io建立了很多次连接,要怎么才能阻止建立这么多呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

问题解决了,删除掉

aSocket.on('disconnect', function () {
      console.log('DISCONNECTED FROM CLIENT');
    });
    
    

或者把它放出exbuffer就行了,而且再也没有setMaxlistener的提示了。
个人不是很明白原理,可能在于一个个嵌套影响,还有disconnect的事件释放不了sockect,所以打印了很多出来。
这个方法有个问题,就是只能一对一,毕竟把socket设置成了全局变量。
直接换成io.emit???

后续待验证。。。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...