Node.js – Socket.io – “最大并发连接数”问题

我有一个socket.io nodejs应用程序的问题(在Windows Azure中)。 它工作正常,但过了一段时间,我得到一个错误,服务器回应为:

HTTP / 1.1 503活动WebSocket请求的数量已达到允许的最大并发WebSocket请求数

  • 我在Windows Azure的基本计划,根据这个职位https://azure.microsoft.com/en-us/blog/introduction-to-websockets-on-windows-azure-web-sites/我可以有350并发连接
  • 我正在使用Windows Azure日志来计算活动套接字,并且在350个套接字已连接(和断开连接)的确切点上,服务器将回应该错误。

服务器设置:

var client_id = 0; var connectCounter = 0; var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); console.log('server init.'); }).listen(port); io = io.listen(server); io.sockets.on('connection', function(socket) { socket.client_id = client_id; client_id++; connectCounter++; console.log('A socket with client_id ' + socket.client_id + ' connected!'); console.log('Sockets counter: ' + connectCounter); socket.on('disconnect', function() { console.log('A socket with client_id ' + socket.client_id + ' disconnected!'); connectCounter--; console.log('Sockets counter: ' + connectCounter); }); }); 

示例日志结尾处:

 A socket with client_id 349 connected! Sockets counter: 1 A socket with client_id 350 connected! Sockets counter: 2 A socket with client_id 349 disconnected! Sockets counter: 1 A socket with client_id 350 disconnected! Sockets counter: 0 

由于我的套接字正在连接和断开连接,所以不应该有350个并发连接。 我做错了什么?

根据我的评论,这个问题可能存在于一个位于engine.io模块中的bug,这个模块是socket.io一个组件。 表面上,原因是engine.io在检测到ping超时时不会closurestcp套接字。

在我发现的一个GitHub的问题中 ,他们显然通过添加一个self.transport.close()调用来修补错误:

 node_modules/socket.io/node_modules/engine.io/lib/socket.js 

应该在你的节点应用程序目录中的某个地方。

我在这个GitHub拉find了一行代码。 代码如下:

 Socket.prototype.setPingTimeout = function () { var self = this; clearTimeout(self.pingTimeoutTimer); self.pingTimeoutTimer = setTimeout(function () { self.onClose('ping timeout'); self.transport.close(); // This is the added line }, self.server.pingInterval + self.server.pingTimeout); }; 

试试看,这可能会解决你的问题。