2012-11-28 7 views
5

i m tạo ứng dụng trò chuyện, sử dụng nodejs (0.8.15), khuôn khổ express (> 3.0) và mongodb cho người dùng đăng ký.nodejs, socket.io: cách nhận yêu cầu và phản hồi từ chức năng socket?

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

Hỏi: Cách nhận lại và xử lý đối tượng để làm việc với họ khi trò chuyện như trên mã ở trên? hoặc tôi đang đi sai cách tạo chat với auth người dùng?

cảm ơn bạn!

EDITED: Câu trả lời là đây http://www.danielbaulig.de/socket-ioexpress/

Trả lời

4

Bạn không thể nhận res và các đối tượng req trong một handler socket.io, vì họ chỉ đơn giản là không tồn tại - socket.io không phải là bình thường http.

Thay vào đó, những gì bạn có thể làm là xác thực người dùng và gán cho họ mã thông báo xác thực phiên (khóa xác định rằng họ đã đăng nhập và họ là ai). Sau đó, khách hàng có thể gửi mã thông báo auth cùng với mỗi tin nhắn socket.io, và xử lý server-side chỉ có thể kiểm tra tính hợp lệ của chủ chốt trong cơ sở dữ liệu:

3

Bạn cần phải sử dụng 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 
}); 
-1

trên socket.io v1.0 trở lên bạn có thể nhận được các đối tượng req như thế này

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

này là sai. Đây không phải là yêu cầu tương tự đang được hỏi trong câu hỏi. Bạn sẽ không tìm thấy tham số yêu cầu của mình ở trên socket.request. –