2013-03-30 4 views
0

Node.js, express 및 sockets.io를 사용하여 뉴스 피드를 만들려고합니다.사용자 특정 뉴스 피드 socket.io 및 node.js

제 문제는 socket.on("connection", function{});이 세션 ID를 제공하지 않기 때문에 연결된 사용자를 알 수있는 방법이 없습니다. 세션에서 연결시 사용자 ID를 전달하는 방법이 있는지 알고 싶습니다.

사용자 ID로 메시지를 수신하면 즉시 서버에 메시지를 보내고 클라이언트 측에서 소켓을 연결하는 방법에 대해 생각해 봤습니다. 사용자 ID로 메시지를 수신하면 서버가 적절한 뉴스 피드 항목을 다시 보냅니다.

더 나은 확장 성/효율적인 방법이 있는지 알고 싶습니다.

+0

안녕하세요, 귀하의 질문을 바꿔보십시오, 텍스트의 벽으로 읽기가 어렵습니다. –

답변

2

socket.io 요청을 승인하면 사용자를 필터링 할 수 있습니다.

당신은 passportSocketIO에서 socket.io

passport.serializeUser(function (user, done) { 
    done(null, user.id); 
}); 

passport.deserializeUser(function (id, done) { 
    User.findById(id, function (err, user) { 
     done(err, user); 
    }); 
}); 

봐와 속성에 액세스하기 위해, 직렬화 사용자 개체를 직렬화해야합니다. 이와 같이 들어오는 socket.io 요청에 권한을 설정할 수 있습니다.

sio.set("authorization", passportSocketIo.authorize({ 
    key: 'express.sid',  //the cookie where express (or connect) stores its session id. 
    secret: 'my session secret', //the session secret to parse the cookie 
    store: mySessionStore,  //the session store that express uses 
    fail: function(data, accept) {  // *optional* callbacks on success or fail 
     accept(null, false);    // second param takes boolean on whether or not to allow handshake 
    }, 
    success: function(data, accept) { 
     accept(null, true); 
    } 
    })); 

그런 다음 '연결'콜백으로 사용자를 필터링 할 수 있습니다.

sio.sockets.on("connection", function(socket){ 
    console.log("user connected: ", socket.handshake.user.name); 

    //filter sockets by user... 
    var userProperty = socket.handshake.user.property,    //property 
     // you can use user's property here. 

    //filter users with specific property 
    passportSocketIo.filterSocketsByUser(sio, function (user) { 
     return user.property=== propertyValue;     //filter users with specific property 
    }).forEach(function(s){ 
     s.send("msg"); 
    }); 

    });