socket.io请求在一段时间后出错


构建了一个实时应用,部署在服务器上面,但是每次运行一段时间后socket.io就报错了,错误是这样的

clipboard.png
前面都是正常的,某一时刻突然就不行了,重启node才行,经常这样
socket.io版本是1.3.5,node版本是0.10.29,node代码是这样的,
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
var user = {},
bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/test', function(req, res) {
var msgBody = JSON.parse(req.param('message'));
console.log(msgBody);
console.log(new Date());
io.emit('chat message', msgBody);
res.send('hello world');
console.log(new Date());
});

io.on('connection', function(socket) {
console.log('connecting');
socket.on('chat message', function(msg) {
console.log(msg);
io.emit('chat message', msg);
});
});

http.listen(4012, function() {
console.log('listening on *:4012');
});
客户端的代码如下:
var socket = io.connect(' http://localhost:4012 ');

第一次发帖。。实在不知道怎么办,求帮助,万分感谢!

node.js JavaScript socket

真夜中的晓 9 years ago

从截图和代码很难定位出真正原因,不知道 node 那边服务器压力是否过大,也不知道是不是因为 node 资源耗尽了造成的问题,最好多在 node 里面打日志来确定究竟在哪一步失败了,特别是把 socket.io 的 error 等时间响应一下,输出日志。

代码看上去没有明显问题,这是 socket.io 的典型用法。截图上看有几个值得尝试的改动:

  • 不是说 socket.io 1.3.5 么,为什么截图里面是 socket.io-1.2.0?会不会客户端和服务端版本不匹配?
  • 你可以设置客户端的 transport 选择顺序为 ["websocket", "polling"] ,或许能节省不少服务器资源。
记忆Edda answered 9 years ago

做过一个聊天应用,给你参考参考: https://github.com/yuanzm/Live-Chat

flour answered 9 years ago

Your Answer