这两天利用socket.io写了一个简易的网页流量监听(express+mongodb):
数据集 var Clicks = db.model('click’,new Schema({ intime:{type:Date,default:Date.now} //进入时间 ,referrer:String //上一步url = 入口 ,outtime:{type:Date,default:Date.now} //退出时间 ,address:String //ip地址 ,user:String //暂时用ip地址代替 })); status文件(设置mongoose连接mongodb):
var collection = "blog"; var mongoose = require(‘mongoose’); //mongoose.connect(‘mongodb://localhost/blog’); var db = mongoose.createConnection('mongodb://localhost/’+collection);
module.exports = { mongoose:mongoose ,db:db };
后台操作数据库采用的是mongoose操作mongodb
var status = require(‘./…/status’); var mongoose = status.mongoose; var db = status.db; var Schema = mongoose.Schema; var Clicks…//数据集模型 var User = function(){}
User.prototype.intoclick=function(referrer,dd){ //用户链接成功后 //var ip = req.connection.remoteAddress; var d = Date(); var click = new Clicks ({intime:d,outtime:d,referrer:referrer,address:dd.ip,user:dd.ip}); click.save(function(err){ //var re = false; if(err){ console.log(err); return false; }else{
Clicks.find({ intime: d}, function (err, docs) {
if(err){
console.log(err);
return false;
}else{
dd._id =docs[0]._id;
}
});
}
}); }
User.prototype.outclick=function(dd){ //用户断开连接 var d = Date(); var click = new Clicks ({outtime:d}); console.log(dd._id); Clicks.update({_id:dd._id},{$set:{outtime:d}} ,function(err){ if(err){ console.log(err); }else{ console.log(dd._id); } }); }
socket.io监听: var User = require(“./…/moudels/user.js”); module.exports = function(io,app){ //app为express的get post用 io.sockets.on('connection’, function (socket) { var dd = {ip:socket.handshake.address.address,_id:0}; socket.on('intoclick’, function (data) { User.intoclick(data.referrer,dd); }); socket.on('disconnect’, function (socket) { User.outclick(dd); }); }); }
前端: window.onload=function(){ var socket = io.connect(‘http://localhost’); socket.emit('intoclick’, { referrer:document.referrer||"" }); }
@ggaaooppeenngg 保持长连接用的,可以设置,socket.io默认的应该是25,让不断和进行非常微量的通信,让服务器知道这个连接还在保持。不然你觉得为什么你能监听disconnect和reconnect呢