gpt4 book ai didi

node.js - socket.get() 和 socket.set() 出现问题

转载 作者:搜寻专家 更新时间:2023-10-31 22:29:20 24 4
gpt4 key购买 nike

我正在使用 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"
});
});

完整代码

http://pastebin.com/vJx7MYfE

最佳答案

您必须直接在套接字中设置昵称属性!

来自 socket.io 网站:

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

此外,来自 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

关于node.js - socket.get() 和 socket.set() 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com