your programing

socket.io를 사용하여 특정 클라이언트에 메시지를 보내는 방법

lovepro 2020. 9. 25. 23:24
반응형

socket.io를 사용하여 특정 클라이언트에 메시지를 보내는 방법


나는 socket.io + node.js로 시작하고, 로컬로 메시지를 보내고 socket.broadcast.emit()기능 을 브로드 캐스트하는 방법을 알고 있습니다 .-연결된 모든 클라이언트가 동일한 메시지를받습니다.

이제 특정 클라이언트에게 개인 메시지를 보내는 방법을 알고 싶습니다. 즉, 두 사람 (Client-To-Client 스트림) 간의 개인 채팅을위한 소켓 하나를 의미합니다. 감사.


사용자가 연결되면 이메일과 같이 고유해야하는 사용자 이름으로 서버에 메시지를 보내야합니다.

사용자 이름과 소켓 쌍은 다음과 같은 객체에 저장되어야합니다.

var users = {
    'userA@example.com': [socket object],
    'userB@example.com': [socket object],
    'userC@example.com': [socket object]
}

클라이언트에서 다음 데이터를 사용하여 서버에 개체를 내 보냅니다.

{
    to:[the other receiver's username as a string],
    from:[the person who sent the message as string],
    message:[the message to be sent as string]
}

서버에서 메시지를 수신합니다. 메시지가 수신되면 데이터를 수신자에게 내 보냅니다.

users[data.to].emit('receivedMessage', data)

클라이언트에서 'receivedMessage'라는 서버의 방출을 수신하고 데이터를 읽음으로써 누가 보낸 사람과 보낸 메시지를 처리 ​​할 수 ​​있습니다.


socket.io 방을 사용할 수 있습니다. 클라이언트 측에서 고유 식별자 (이메일, ID)를 사용하여 이벤트 (이 경우 "조인"은 무엇이든 가능)를 내 보냅니다.

고객 입장에서:

var socket = io.connect('http://localhost');
socket.emit('join', {email: user1@example.com});

이제 서버 측에서 해당 정보를 사용하여 해당 사용자를위한 고유 한 공간을 만듭니다.

서버 측:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.on('join', function (data) {
    socket.join(data.email); // We are using room of socket io
  });
});

따라서 이제 모든 사용자가 사용자의 이메일 이름을 딴 방에 참여했습니다. 따라서 특정 사용자에게 메시지를 보내려면

서버 측:

io.sockets.in('user1@example.com').emit('new_msg', {msg: 'hello'});

클라이언트 측에서 마지막으로 할 일은 "new_msg"이벤트를 수신하는 것입니다.

고객 입장에서:

socket.on("new_msg", function(data) {
    alert(data.msg);
}

나는 당신이 아이디어를 얻길 바랍니다.


확실히 : 간단히 말해서

이것이 필요한 것입니다.

io.to(socket.id).emit("event", data);

whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.

first we need to store all the socket.ids in array,

var people={};

people[name] =  socket.id;

here name is the receiver name. Example:

people["ccccc"]=2387423cjhgfwerwer23;

So, now we can get that socket.id with the receiver name whenever we are sending message:

for this we need to know the receivername. You need to emit receiver name to the server.

final thing is:

 socket.on('chat message', function(data){
io.to(people[data.receiver]).emit('chat message', data.msg);
});

Hope this works well for you.

Good Luck!!


You can refer to socket.io rooms. When you handshaked socket - you can join him to named room, for instance "user.#{userid}".

After that, you can send private message to any client by convenient name, for instance:

io.sockets.in('user.125').emit('new_message', {text: "Hello world"})

In operation above we send "new_message" to user "125".

thanks.


In a project of our company we are using "rooms" approach and it's name is a combination of user ids of all users in a conversation as a unique identifier (our implementation is more like facebook messenger), example:

|id | name |1 | Scott |2 | Susan

"room" name will be "1-2" (ids are ordered Asc.) and on disconnect socket.io automatically cleans up the room

this way you send messages just to that room and only to online (connected) users (less packages sent throughout the server).


Let me make it simpler with socket.io rooms. request a server with a unique identifier to join a server. here we are using an email as a unique identifier.

Client Socket.io

socket.on('connect', function () {
  socket.emit('join', {email: user@example.com});
});

When the user joined a server, create a room for that user

Server Socket.io

io.on('connection', function (socket) {
   socket.on('join', function (data) {    
    socket.join(data.email);
  });
});

Now we are all set with joining. let emit something to from the server to room, so that user can listen.

Server Socket.io

io.to('user@example.com').emit('message', {msg: 'hello world.'});

Let finalize the topic with listening to message event to the client side

socket.on("message", function(data) {
  alert(data.msg);
});

The reference from Socket.io rooms

참고URL : https://stackoverflow.com/questions/17476294/how-to-send-a-message-to-a-particular-client-with-socket-io

반응형