admin管理员组文章数量:1327660
I've been working on a game and i'm using sockets for some simple backend stuff. One issue i noticed is that when a player dies, i emit a socket requesting to reset the game. the issue is, this gets sent to everyone, so when one person dies, everyone gets sent back to the home screen.
How can i make it so that (io.emit - the server) only affects the (socket.on - the client)?
My heart stopped when i realized this, i've gotten so far and i can't believe this hadn't crossed my mind!
I've been working on a game and i'm using sockets for some simple backend stuff. One issue i noticed is that when a player dies, i emit a socket requesting to reset the game. the issue is, this gets sent to everyone, so when one person dies, everyone gets sent back to the home screen.
How can i make it so that (io.emit - the server) only affects the (socket.on - the client)?
My heart stopped when i realized this, i've gotten so far and i can't believe this hadn't crossed my mind!
Share Improve this question asked Apr 9, 2020 at 8:16 PylotPylot 2611 gold badge3 silver badges18 bronze badges 2- you have to create a separate room for everyone and then emit the event accordingly. – mehta-rohan Commented Apr 9, 2020 at 8:33
- This has been answered here: stackoverflow./questions/4647348/… – Lucas S. Commented Apr 9, 2020 at 9:31
1 Answer
Reset to default 5I guess one of the ments directs you to a few potential answers. But just in case a struggling coder has the same issue, here is what i did that resolved it.
server.js
io.on('connection', function(socket) {
io.to(socket.id).emit('private', `your secret code is ${code}`);
});
client.js
socket.on('private', function(msg) {
alert(msg);
});
https://socket.io/docs/v4/emit-cheatsheet/ has a bunch of useful information in a small amount of text. Also heres the link to the other question in case you want to know more then one solution:
Send message to specific client with socket.io and node.js
本文标签: javascriptHow do i make socketio send emit message to only one clientStack Overflow
版权声明:本文标题:javascript - How do i make socket.io send emit message to only one client? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742228605a2436795.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论