CakePHP Server Sent Events for Live notifications - OneNightStudy.Com

Monday, 13 April 2015

CakePHP Server Sent Events for Live notifications

Server Sent events is the way to automatically to send request to server and get response after regular time interval.SSEs are uses HTTP protocol i.e it does not require special server like socket. Best use is get live notification from server. For example if we have social networking site and we need friend request notification or accept notification.

How to use steps :
1. Let suppose we are working in friends controller then in the action get_friend_request_count:

function get_friend_request_count($user_id){
header('Content-Type: text/event-stream'); 
header('Cache-Control: no-cache');
//example query 
 $friend_count = $this->friend->find('count',array('conditions'=>array('user_id'=>$user_id)));
echo "retry: 5000\n data: Friend count : { $friend_count}\n\n";

2. Write a javascript code that is available every where or in the layout:

<div id="friend_count"></div>
<script tye="text/javascript">
         var source=new EventSource('localhost/friends/get_friend_request_count'); //modify path as correct path
      alert('Server sent event does not work with IE')

No comments:

Post a Comment