express4下socket.io的验证
node实战里面有socket.io+angular.js的聊天室例子,但是现在express和socket.io的版本都发生了不小的变化,自己写了个express4下的socket.io验证
不废话,贴代码
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var async = require('async');
var app = express();
var config = require('./config');
var cookie = require('cookie');
var session = require('express-session');
var mongoose = require('mongoose');
var users = require('./routes/users');
var UserModel = require('./Dao/user')();
var MongoStore = require('connect-mongo')(session);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//连接数据库
mongoose.connect(config.dbPath, function onMongooseError(err) {if (err) throw err;
});
var sessionStore = new MongoStore({url: 'mongodb://localhost/technode'
});
app.use(session({secret: 'technode',cookie: {maxAge: 60 * 1000},store:sessionStore,resave: true,saveUninitialized: true
}));
app.use('/users', users);app.get('/',function (req, res) {res.sendfile('./static/index.html')
});var io= require("socket.io").listen(app.listen(8000));
io.set('authorization', function(handshakeData, accept) {var cookies = cookie.parse(handshakeData.headers.cookie); //解析cookiesvar connectSid = cookies['connect.sid'];if(connectSid){//判断有无session登陆var connected = cookieParser.signedCookie(connectSid, 'technode');//验证session的secretif(connected){sessionStore.get(connected, function (error, session) { //去session里面取当前用户的数据if (error) {accept(error.message, false)} else {handshakeData.headers.sessions = session; //把当前用户数据传给socket.io的handshakeDataif (session.user) {accept(null, true)//进行下面的链接} else {accept('No login',false)}}})}else {accept('No session',false)//没session}}});
var SYSTEM = {account: '机器人'
}
var messages = [];
io.sockets.on('connection', function (socket) {socket.on('init', function () {socket.emit('init', messages);if(socket.handshake.headers.sessions!=null){ //如果有用户信息,确认登陆,执行操作var user = socket.handshake.headers.sessions.user;socket.broadcast.emit('messages.add',{content: user.account + '进入了聊天室',creator: SYSTEM,createAt: new Date()});UserModel.modify({account:user.account},{status:1},function(err,doc){UserModel.User.find({status:1},{account:1}, function (err,doc) {if(doc){io.sockets.emit('users.init', doc);}});});}});socket.on('messages.read', function () {socket.emit('messages.read', messages);console.log("read");})socket.on('messages.create', function (message) {messages.push(message);io.sockets.emit('messages.add', message);});socket.on('disconnect', function() {//socket断开的时候,把用户状态设置为离线if(socket.handshake.headers.sessions!=null) {var user = socket.handshake.headers.sessions.user;UserModel.modify({account: user.account}, {status: 0}, function (err, doc) {if (doc != null) {console.log(doc.account + " has disconnect");}});socket.broadcast.emit('users.remove', user);}});
});console.log("TechNode is on port 8000!")
代码在这->
https://github.com/xyc-cn/socket-angular/tree/xyc
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!