PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] How do i make socket.io send emit message to only one client?

 October 22, 2022     javascript, node.js, socket.io, sockets     No comments   

Issue

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!


Solution

I guess one of the comments 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/emit-cheatsheet/ has a bunch of useful information in a small amount of room. also heres the link th the other question in case you want to know more then one solution:

Send message to specific client with socket.io and node.js



Answered By - Pylot
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing