gpt4 book ai didi

javascript - 如何使用 Socket.io 在一条消息中发送两个变量?

转载 作者:IT老高 更新时间:2023-10-28 23:07:08 26 4
gpt4 key购买 nike

我有一个客户端 ID 和用户名,我希望它们都通过套接字发送。

 client.userid = userid;
client.username = username;
client.emit('onconnected', { id: client.userid, name: client.username });

我试过这个,但它似乎不起作用

最佳答案

你可以试试这个

io.sockets.on('connection', function (socket) {
socket.on('event_name', function(data) {
// you can try one of these three options

// this is used to send to all connecting sockets
io.sockets.emit('eventToClient', { id: userid, name: username });
// this is used to send to all connecting sockets except the sending one
socket.broadcast.emit('eventToClient',{ id: userid, name: username });
// this is used to the sending one
socket.emit('eventToClient',{ id: userid, name: username });
}
}

在客户端

 socket.on('eventToClient',function(data) {
// do something with data
var id = data.id
var name = data.name // here, it should be data.name instead of data.username

});

关于javascript - 如何使用 Socket.io 在一条消息中发送两个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20632401/

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