7

我正在创建聊天应用程序,使用 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/

4

3 回答 3

7

你需要使用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
});
于 2013-10-11T17:08:40.193 回答
6

您无法在 socket.io 处理程序中获取 res 和 req 对象,因为它们根本不存在 - socket.io 不是普通的 http。

相反,您可以做的是对用户进行身份验证并为他们分配一个会话身份验证令牌(一个标识他们已登录以及他们是谁的密钥)。然后客户端可以将身份验证令牌与每个 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"
});
于 2012-11-28T22:51:59.580 回答
-2

socket.io v1.0上面你可以得到这样的req对象

var req = socket.request;
var res = req.res;
于 2016-05-26T12:20:50.970 回答