I am currently building an application using node.js and using the socket.io module. When a user connects I am storing data specific to the user against their socket. For example
io.sockets.on('connection', function (socket) {
socket.on('sendmessage', function (data, type) {
socket.variable1 = 'some value';
socket.variable2 = 'Another value';
socket.variable3 = 'Yet another value';
});
});
While this works my question is, is this a good way to do it. I am effectively storing session data but is there a better way to do it?
on("connection", function (socket) { socket. on("save-client-data", function (clientData) { var clientId = clientData. clientId; globalVariable[clientId] = JSON. parse(clientHandshakeData); }); socket.
To emit an event from your client, use the emit function on the socket object. To handle these events, use the on function on the socket object on your server. Sent an event from the client!
Socket.IO allows bi-directional communication between client and server. Bi-directional communications are enabled when a client has Socket.IO in the browser, and a server has also integrated the Socket.IO package. While data can be sent in a number of forms, JSON is the simplest.
Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more.
I think that you should store those variables in another type of object. Keep the socket object only for the communication. You may generate an unique id for every user and create a map. Something like this:
var map = {},
numOfUsers = 0;
io.sockets.on('connection', function (socket) {
numOfUsers += 1;
var user = map["user" + numOfUsers] = {};
socket.on('sendmessage', function (data, type) {
user.variable1 = 'some value';
user.variable2 = 'Another value';
user.variable3 = 'Yet another value';
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With