我正在使用NodeJs v0.10.28,每当我尝试登录聊天时都会收到错误
TypeError: Object #<Socket> has no method 'set' at Socket.<anonymous>
如果我删除了它的工作线但是没有正常工作。
此代码中的错误是什么
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
console.log('error ', err);
sender = name;
});
和
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "Welcome, " + name + '!',
msgr : "Nickname"
});
});
完整代码
答案 0 :(得分:8)
您必须直接在套接字中设置nickname属性!
来自socket.io网站:
旧的io.set()和io.get()方法已弃用,仅支持向后兼容。以下是旧授权示例到中间件样式的翻译。
另外,从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's 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
});
});
查看此处的示例:https://github.com/Automattic/socket.io/blob/master/examples/chat/index.js
答案 1 :(得分:3)
与Ludo所说的一样,直接在套接字中设置nickname属性:
// get the name of the sender
var name = socket.nickname;
console.log('Chat message by ', name);
console.log('error ', err);
sender = name;
和
// this kind of emit will send to all! :D
socket.nickname = name;
io.sockets.emit('chat', {
msg : "Welcome, " + name + '!',
msgr : "Nickname"
});