我希望客户端每30秒连接一次到服务器并建立新连接。我想更改用户断开连接的时间。
客户端:
<script>
var socket = io.connect('http://localhost:3000', {
'reconnect': true,
'force new connection': true
});
socket.on('connect', function (data) {
socket.emit('storeClientInfo', { customId:"123456789",'sessionId':"asd2131ad113ad" });
});
</script>
服务器端:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var exec = require("child_process");
var people = [];
io.on('connection', function(socket){
var peop = {};
socket.on('storeClientInfo', function (data) {
var status = new Date().getTime();
console.log('login:' +status);
socket.on('disconnect', function(){
var status = new Date().getTime();
console.log('logout:' +status);
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
输出登录信息:
login:1416837382116
logout:1416837407535
login:1416837410118
logout:1416837435537
login:1416837438115
必须在30秒后完成注销。 我尝试改变这些值:
io.set('heartbeat timeout', );
io.set('heartbeat interval', );
但我没有成功获得正确的结果。
编辑后的代码:
io.on('connection', function(socket){
socket.on('storeClientInfo', function (data) {
var userId = data.customId;
var userIpAddress= socket.request.socket.remoteAddress;
var status = new Date().getTime()+65000;
if (typeof people[userId] == 'undefined') {
people[userId] = {userId: userId,status:status};
console.log(userId + ' logged. Ip address: '+ userIpAddress);
} else {
people[userId] = {userId: userId,status:status};
}
socket.on('disconnect', function(){
setTimeout(function () {
var now = new Date().getTime();
if (typeof people[userId] != 'undefined'){
if (people[userId].status < now) {
exec.exec("php some.php " + data.customId, function(err, stdout, stderr) { console.log(userId + " logout!"); });
delete people[userId];
}
}
}, 125000);
});
});
});