[英]How to change 'deprecated set() and get() in old socket.io code?
I'm new to node/socket.io and working with an old tutorial to make a chatroom. 我是node / socket.io的新手,并且正在使用旧教程进行聊天室。
Here is socket.js part: 这是socket.js部分:
exports.initialize = function (server) {
io = io.listen(server);
var chatInfra = io.of("/chat_infra")
.on("connection", function(socket){
socket.on("set_name", function (data) {
socket.set('nickname', data.name, function () {
socket.emit('name_set', data);
socket.send(JSON.stringify({type:'serverMessage',
message:'Welcome to the most interesting ' +
'chat room on earth!'}));
socket.broadcast.emit('user_entered', data);
});
});
});
var chatCom = io.of("/chat_com")
.on("connection", function (socket) {
socket.on('message', function (message) {
message = JSON.parse(message);
if (message.type == "userMessage") {
socket.get('nickname', function (err, nickname) {
message.username = nickname;
socket.broadcast.send(JSON.stringify(message));
message.type = "myMessage";
socket.send(JSON.stringify(message));
});
}
});
});
}
But I get 但是我明白了
TypeError: Object #<Socket> has no method 'set'
at Socket.<anonymous> (/home/me/awesome-chat/routes/sockets.js:9:18)
I am using "socket.io": "^1.4.8"
and I know that set()
is deprecated so I tried to chage the set part to use .use()
as per docs example, but I had no luck in that and got: 我正在使用"socket.io": "^1.4.8"
并且我知道set()
已被弃用,所以我尝试按照文档示例修改.use()
使用.use()
,但是我没有运气并得到:
TypeError: Object #<Socket> has no method 'use'
The same goes for the .get() part. .get()部分也是如此。 So I'm really perplexed and appreciate your hints. 所以我真的很困惑,感谢您的提示。
Socket#set
andSocket#get
are not a method of Socket.IO , so it can't be used.Socket#set
和Socket#get
不是Socket.IO的方法,因此无法使用。 Then have to remove those methods. 然后必须删除那些方法。
you can assign that stuff like this 你可以像这样分配东西
socket.nickName = 'Hola' and read it as it is socket.nickName ='Hola'并按原样读取
For getting that value in your code, you can do something like this 为了在代码中获得该值,您可以执行以下操作
.on("connection", function (socket) {
socket.on('message', function (message) {
message = JSON.parse(message);
if (message.type == "userMessage") {
if(socket && socket.nickname){
message.username = socket.nickname;
socket.broadcast.send(JSON.stringify(message));
message.type = "myMessage";
socket.send(JSON.stringify(message));
};
}
});
});
Please see the Socket.IO API
for details 请参阅Socket.IO API
以获取详细信息
And here is updated libs of Socket.io 这是Socket.io的更新库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.