Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

node.js - Adding a cookie value on Socket.IO

How to add a cookie value on Socket.IO?

io.sockets.on('connection', function (client)
{ 
    console.log(client.id); 
    client.handshake.headers.cookie.socketID = client.id;   // not work
 // client.handshake.headers.cookie("socketID",client.id);  //crash

    console.log(client.handshake.headers.cookie);
// The current output is:
//connect.sid=tI21xumy3u2n4QXO1GljmPAf.pzFQ1Xu%2B6bz36secu4VSCdSNU8PT1L44gQZ4kFUFQqQ
//this is express session id, and I also want to add client.id of Socket.IO. 

//...........
}

I have read http://www.danielbaulig.de/socket-ioexpress/ , but I do not need session management on node.js, but just need to add a socket.io client ID value in cookie as connect.sid does.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a look at Authorization with Socket.io. This is where it handles the initial connection request, and where you can set a response header.

I'm not sure if the cookie(name,value) shorthand works, though you can try setting it manually:

    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000)); // set day value to expiry
    var expires = "; expires="+date.toGMTString();

    handshake.headers.cookie = name+"="+value+expires+"; path=/";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...