How to broadcast to a specific socketid or user?
neovash23 opened this issue · comments
is there a way to implement something like this:
socket.broadcast.to(id).emit('my message', msg);
or do I create rooms dynamically?
Hello, It easy. Use "EventRoomInterface". You can set to $data some "user_id", so event will be:
class CountEvent implements EventInterface, EventPubInterface, EventRoomInterface
{
...
protected $userId;
/**
* Socket.io room
* @return string
*/
public function room(): string
{
return 'user_id_' . $this->userId;
}
/**
* Emit client event
* @param array $data
* @return array
*/
public function fire(array $data): array
{
$this->userId = $data['userId'];
return [
'count' => 10
];
}
...
}
Client side:
var socket = io('localhost:1367/notifications');
socket.emit('join', {room: 'user_id_<?= Yii::$app->user->getId()// For example id 10 ?>'});
// Now you will receive data from user
socket.on('update_notification_count', function(data){
console.log(data)
});
//Run broadcast to client. Only user with id 10 will receive count = 10
\yiicod\socketio\Broadcast::emit(CountEvent::name(), ['count' => 10, 'userId' => 10])
Any other user will not receive data.
This is great, thank you for that!