0

I am new to PusherJS and developing a real-time chat app using PHP. Everything working fine but when I press enter to send message, it append it in sender's box and into receiver's box also. How I can differentiate it on the basis of session or user_id. See there are same message is sender and receiver's box: enter image description here

Real-Time.php:

$options = array(
    'cluster' => 'ap2',
    'useTLS' => true
);
$pusher = new Pusher\Pusher(
    'c575a7********edb87d',
    '8fee27********57fdd2',
    '7***6*',
    $options
);
$pusher->trigger('channel', 'event', $data);

The .js file:

var pusher = new Pusher('c575a76********db87d', {
    cluster: 'ap2',
    forceTLS: true
});
var channel = pusher.subscribe('channel');
channel.bind('event', function(data) {

    var msg_template = ``; //<-- Just removed template it's simple HTML

    $("ul#messages").append(msg_template);
});

1 Answers1

0

You need to restrict the message sender from receiving the broadcasted message. How to do so is documented at on the Pusher website.

First, you need to store the SocketID when connecting to Channels:

var pusher = new Pusher('APP_KEY');
var socketId = null;
pusher.connection.bind('connected', function() {
  socketId = pusher.connection.socket_id;
});

Once this has been found, you can use it in the event sent to the server:

data: {
      id: 'some_id',
      updated_value: 'some_value',
      socket_id: socketId // pass socket_id parameter to be used by server
    }

This will then prevent the client with that socketId from receiving the message.

doydoy
  • 4,021
  • 3
  • 20
  • 33