node.js - nodejs,socket.io : how to get request and response from socket function?

标签 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/

最佳答案

您需要使用授权

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

关于node.js - nodejs,socket.io : how to get request and response from socket function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13615280/

相关文章:

javascript - 处理订单队列 (Redis) 的最佳选择是什么?

javascript - 使用 Promise 确保文件流已结束

javascript - 让 grun-express 重新启动更改

node.js - 客户端找不到io

node.js - 带有 Express 框架的 Node.js 中的自定义事件

javascript - LAME 编码器 Node.js MP3 流

android - 尝试在 Ubuntu 13.04 上运行 Phonegap

Node.js 路径错误

node.js - 在express中,当表单有破折号时如何从表单中获取属性名称?

javascript - 是否可以使用 socket.io 取消订阅 MtGox API channel ?