Socket.get () and socket.set () gives problems

I use NodeJs v0.10.28, and every time I try to enter the chat, I get an error

TypeError: Object #<Socket> has no method 'set' at Socket.<anonymous>

And if I delete the lines, this works, but does not work correctly.

What's wrong with this code

 // get the name of the sender socket.get('nickname', function (err, name) { console.log('Chat message by ', name); console.log('error ', err); sender = name; }); 

and

 socket.set('nickname', name, function () { // this kind of emit will send to all! :D io.sockets.emit('chat', { msg : "Welcome, " + name + '!', msgr : "Nickname" }); }); 

FULL CODE

http://pastebin.com/vJx7MYfE

+6
source share
2 answers

You must set the nickname property directly on the socket!

From socket.io:

The old io.set () and io.get () methods are deprecated and are only supported for backward compatibility. Here is a translation of the old authorization example into the middleware style.

Also, using the example website socket.io:

 // usernames which are currently connected to the chat var usernames = {}; var numUsers = 0; // when the client emits 'add user', this listens and executes socket.on('add user', function (username) { // we store the username in the socket session for this client socket.username = username; // add the client username to the global list usernames[username] = username; ++numUsers; addedUser = true; socket.emit('login', { numUsers: numUsers }); // echo globally (all clients) that a person has connected socket.broadcast.emit('user joined', { username: socket.username, numUsers: numUsers }); }); 

See an example here: https://github.com/Automattic/socket.io/blob/master/examples/chat/index.js

+8
source

Like what Ludo said, set the nickname property directly on the socket:

 // get the name of the sender var name = socket.nickname; console.log('Chat message by ', name); console.log('error ', err); sender = name; 

and

 // this kind of emit will send to all! :D socket.nickname = name; io.sockets.emit('chat', { msg : "Welcome, " + name + '!', msgr : "Nickname" }); 
+3
source

Source: https://habr.com/ru/post/970133/


All Articles