简体   繁体   中英

What is the scope of socket.emit()?

We're using Socket.IO for a chat application. Who will receive a message that is sent through socket.emit() ? Over here , it is given like, socket.emit() will send a message only to one client.

Our requirement is achieving one to one communication (between a user and server and not between two users). Currently, we are creating separate rooms for different users and sending messages using io.in(room).emit() . The messages will be sent to everyone in that room and as per our application, a room will have only one user.

Can we achieve the same using socket.emit() by creating a single room and manage to respond to the particular client?

UPDATE:-

For more clarification, here is a scenario.

Five different users opens the chat box and everyone asks a different question to the server. We create five different rooms (one for a user) and respond to the users using io.in(room).emit() .

So, actually what we are doing here is, in the server side, we are identifying the users based on the room in which he is present. Is there a better way here? Heard socket.emit() will only respond to one client and was wondering whether it would ease our problem.

According to your requirement, User sends data to the server only. You use emit event in client side and on event in a server with the same method.

Client

Client emit method

socket.emit('DataClientToServer',{data : 'hello'});

Client on method, get data from server

socket.on('DataServerToClient',function(data){
            console.log(data);
        });

Server

Server on method to get that data and send data to that client only using socket.id

socket.on('DataClientToServer', (data) => {
            console.log(data);
            //Send data to that client only using socket.id
            io.to(socket.id).emit('DataServerToClient',{data : 'Server to Client'});
        });

For Detect which user send data, you send extra data like user unique username or userid or objectid etc.

Not needed room every user.

Hope this help you.

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