nodejs,socket.io:如何从套接字函数获取请求和响应?

即时通讯创build聊天应用程序,使用nodejs(0.8.15),expression(> 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对象来与他们一起工作? 或者我会错误的方式与用户身份validation创build聊天?

谢谢!

编辑:答案在这里http://www.danielbaulig.de/socket-ioexpress/

你不能在socket.io处理程序中获取res和req对象,因为它们根本就不存在 – socket.io不是普通的http。

相反,你可以做的是对用户进行身份validation,并为他们分配一个会话授权令牌(一个标识他们已经login的密钥和他们是谁)。 然后,客户端可以发送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" }); 

您需要使用authorization

 var socketIO = require('socket.io').listen(port); socketIO.set('authorization', function(handshakeData, cb) { //use handshakeData to authorize this connection //Node.js style "cb". ie: if auth is not successful, then cb('Not Successful'); //else cb(null, true); //2nd param "true" matters, i guess!! }); socketIO.on('connection', function (socket) { //do your usual stuff here }); 

socket.io v1.0及以上版本,你可以得到这样的req对象

 var req = socket.request; var res = req.res;