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

时间:2012-11-28 22:09:18

标签: node.js express socket.io

我正在创建聊天应用程序,使用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对象与它们一起使用?或者我是否错误地使用用户身份验证创建聊天?

谢谢你!

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

3 个答案:

答案 0 :(得分:5)

你不能在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"
});

答案 1 :(得分:4)

您需要使用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
});

答案 2 :(得分:-1)

socket.io v1.0及以上,您可以获得req这样的对象

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