Search code examples
javascriptjqueryserver-sent-events

how to differentiate between different server sent event listeners?


I have a application in which different user listens to server sent event source for a periodical response .I intend to sent response from server with corresponding Id and data in json format.And at client side each client when data arrives checks for matching Id if found it process the data else ignore it.But the flaw in this approach is each user gets data from periodical updates even if it is not intended for them.I read a few articles about sse but could't find anything about this

My question is using server side events is there any way of sending response to specific listeners and if so how .?


Solution

  • What I did was to register the user /ask the user for login and return a unique Identification key.Using this key as event name event listener is initialized in the post back success function of registration/login $post();.

    So basically each event listener listen to a unique event .At server side each event name is broadcasted followed by data so unique event listeners get messages only intended for them.

    Clientside

    $.post( "chatReg.php", { xxx: xxxx, time: xxx}).done(function( data ) {
    
         if((typeof(EventSource) !== "undefined")&&((localStorage.getItem("uname") !== null))) {
        var source = new EventSource("XXXXXXXX.php");   
    
        source.addEventListener(localStorage.getItem("uname"), function(e) {
         var data = JSON.parse(e.data);
    
         $('div.chat-box-content').append('<div class="msgWrapper"><div class="msgwrapperleft"><div class="iconright"><img src="http://placehold.it/40X40"></img></div><div class="MessageRight">'+data.Message+ '</div> </div><p class="ArrivedTimeRight"><span ><span class="timeago" >'+CreateTimestamp()+'</span></span></p></div>');
    
        }, false);
    
    
        } 
    
    }
    

    Server

    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');
    header("refresh: 5;");
    
        echo  'event: '.$row['SpecialId'];
                echo PHP_EOL;
    
                echo  'data: {"Message":"'.$row['Message'].'","xxxId":"'.$row['xxxId'].'"}';
                echo PHP_EOL;
                echo PHP_EOL;