我正在创建聊天应用程序,使用nodejs(0.8.15),express(> 3.0)框架和
mongodb用于注册用户.
var express = require('express'),http = require('http'),path = require('path'),io = require('socket.io'); var app = express(),server = http.createServer(app),io = io.listen(server); app.configure(function() { app.set('port',process.env.PORT || 3000); app.set('views',__dirname + '/views'); app.set('view engine','ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('secret')); app.use(express.session({cookie: {maxAge: 60000*100}})); app.use(app.router); app.use(express.static(path.join(__dirname,'public'))); }); app.configure('development',function() { app.use(express.errorHandler()); }); app.get('/chat',function(req,res) { res.render('chat'); }); server.listen(app.get('port'),function() { console.log("Express server listening on port " + app.get('port')); }); io.sockets.on('connection',function (socket) { socket.on('start-chat',function() { // here i need to know req and res // for example,i need to write: // socket.username = req.session.username; }); });
问:如何在上面的代码聊天时获取res和req对象与它们一起工作?或者我错误的方式与用户身份验证创建聊天?
谢谢!
解决方法
你不能在socket.io处理程序中获取res和req对象,因为它们根本不存在 – socket.io不是普通的http.
相反,您可以做的是对用户进行身份验证并为其分配会话身份验证令牌(一个标识他们已登录的密钥以及他们是谁).
然后客户端可以发送auth令牌以及每个socket.io消息,服务器端处理程序可以只检查数据库中密钥的有效性:
io.sockets.on('connection',function (socket) { socket.on('start-chat',function(message) { if (message.auth_token) //Verify the auth_token with the database of your choice here! else //Return an error message "Not Authenticated" });