NodeJS,Socket.IO:如何从socket函数中获取请求和响应?

7

我正在创建一个聊天应用,使用的是Node.js(版本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个回答

7

您需要使用 授权

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
});

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"
});

-2
socket.io v1.0 及以上版本中,您可以通过以下方式获取 req 对象。
var req = socket.request;
var res = req.res;

1
这是错误的。这不是问题中所要求的相同请求。您将无法在上述socket.request中找到您的请求参数。 - Rajeev Jayaswal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接