简体   繁体   中英

Socket.io, message to yourself

Socket.io doesn't display messages send on yourself ip. For example

var id = 333;
socket.broadcast.to(id).emit('user', user);

It working good, but message is only in client #333, but user than sent message, do not have a copy in the message client.

I wanted to solve in this way, but it does not work

socket.broadcast.to(socket.id).emit('user', user);

Why?

Without more code its hard to say what you want but one thing is certain in order to send a message to a single user you must use that socket object and use socket.emit

As far as i know broadcast is only used to tell everyone except for yourself.

What i usually do when it comes to keeping track of users is i have the following:

    var userList = [];
io.on('connection', function (socket) {

    socket.on('userData', function (userDetails) {
        userDetails.socket = socket;
        userList[userDetails.id] = userDetails
    });
});

Basicly when a user connects to my socket and the page for the user is fully loaded it sends its id (or a token if you wish) i then map the user's socket into the list so i can quickly pick it up again if i wish to send to that user.


An example could be:

user.id = 33 connects to our server

Once loaded the users emits to our server userData function

The socket is then taken and put into the list at row 33

When we need to we can this use the following code to get the users socket :

socket = userList[33];

or if we have the object:

socket = userList[user.id];

I hope this helps you.

For this, you can use socket.emit('message') .

socket.emit: Emit for only one socket.

Hope this will help you. You can also check out this link: socket.io send packet to sender only

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