简体   繁体   中英

How to make socket.on() function in server.js happen to a the person that emitted it? (Node.js)

When i emit something like this in my app.js file :

socket.emit('3');

The function happens to everyone in the game.

server.js function:

    socket.on('3', function() {
    global.cashing = true;
});

I tested if the app.js socket.emit() function was happening to everyone too by placing a window.location.replace in the function, like so:

socket.emit('3');
window.location.replace('otherurl.com');

I observed that the player that emitted the function was the only one that had their location replaced, but the server.js socket.on() function still applied to the all the other players.

So, when i place the socket.emit function, everybody is affected by the socket.on function, but i need this function to apply to one person.

I tried doing something like this:

socket.emit('3', id);

and then,

        socket.on('3', function(id) {
if(arguments.length) {
        global.cashing = true;
}
});

and

        socket.on('3', function(id) {
if(id !== undefined) {
        global.cashing = true;
}
});

And this did not work. The function still applied to all players. (I also tried an if statement with null.

How can i make this socket.on function only apply to the player that emitted it?

Sorry if this is really simple, i'm new to node.js :)

When sockets are initialized they have an id which can be accessed later via server.sockets.sockets[id] . It is up to you to manage correlating those ids with more personalized data that your app can use - make sure if you do an in-memory map you clean up ids when sockets close (and in general, think of ways to scale, because its a thing to think about)!

const app = require("express")();
const http = require("http").Server(app);
const io = require("socket.io")(http);

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

io.on("connection", function(socket) {
  console.log("a user connected", socket.id);
  console.log("welcoming them personally");
  io.sockets.sockets[socket.id].emit("message", "hello " + socket.id);
});

http.listen(3000, function() {
  console.log("listening on *:3000");
});

Then in the UI:

<!doctype html>
<html>

<head>
  <title>Socket.IO chat</title>
</head>
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.on('message', console.log)
</script>

<body>

</body>

</html>

You will see independent UIs log without notifying the others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM