I am trying to implement Server-sent-events communication between my client and my server.
I have implemented it and it works perfectly except when the server return exceptions.
I am not sure why the exception message is not being returned to the client after the exception.
Here is how my listener is written
var evtSource = new EventSource('poll.php');
evtSource.addEventListener("getMessagingQueue", function(e) {
console.log(e);
var data = JSON.parse(e.data);
console.log(data);
processServerData(data);
}, false);
Below is my PHP code. (ie. poll.php
) file
ini_set('display_errors', 0);
set_time_limit(0);
header("Content-Type: text/event-stream" . PHP_EOL);
header("Cache-Control: no-cache" . PHP_EOL);
try {
$sleepTime = 1;
$url = '';
$loggedIn = false;
if( !isDefinedConstents('ICWS_USERNAME', 'ICWS_PASSWORD', 'ICWS_STATION_NAME', 'ICWS_SERVER', 'ICWS_PORT') ){
throw new exception('Missing Credentials');
} else {
$scheme = 'http';
if(ICWS_SECURED){
$scheme = 'https';
}
$url = sprintf('%s://%s:%s@%s:%s', $scheme, ICWS_USERNAME, ICWS_PASSWORD, ICWS_SERVER, ICWS_PORT);
//configure the connection
$conf = new ICWS\Config\Config($url, ICWS_STATION_NAME);
//create a new instance of icws
$icws = new ICWS\Connection($conf);
$messaging = new ICWS\Messaging($icws);
$loggedIn = $icws->isLogged();
}
if(!$loggedIn){
throw new exception('Something Went Wrong when trying to login');
}
while($loggedIn){
$messaging->processMessages();
$result = array_merge( (array) $messaging->getCallsQueue(), (array) $messaging->getCurrentUserStatusQueue()) ;
displayResults($result);
sleep(1);
}
} catch(Exception $e){
$result = array('userStatus' => array('statusId' => 'You are not logged in!',
'isLoggedIn' => false,
'icwsDescription' => $e
)
);
displayResults($result);
}
function displayResults($result){
echo 'event: getMessagingQueue' . PHP_EOL;
echo 'data: ' . json_encode( $result ) . PHP_EOL . PHP_EOL;
ob_end_flush();
flush();
}
function isDefinedConstents(){
$args = func_get_args();
foreach($args as $v){
$value = constant($v);
if( !defined($v) || empty($value) ){
return false;
}
}
return true;
}
How do I get the listener to get the message even if the there is exceptions?
EDITED When I execute this code after the addEventListner line
evtSource.onerror = function(e) {
console.log(e);
};
This is what I get
error { target: EventSource, isTrusted: true, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, timeStamp: 1435614201283000, originalTarget: EventSource, explicitOriginalTarget: EventSource, NONE: 0 }
It seems that the Exception thrown by PHP server cause the entire call to fail.
I solved the problem by adding
ob_end_clean();
below the twoheader(....
lines