2017-11-08 1 views
0

PHP로 JS Server-Sent_Events를 사용하는 시스템을 설정 중입니다. 그리고 잘 작동합니다. 그러나 모든 일에 오류 이벤트가 발생하면 한 번 발생하고 이유를 이해할 수 없습니다.js server를 사용하여 PHP로 이벤트를 보낸 지 정하지 않은 sse 오류가 나타나는 이유는 무엇입니까?

내 JS는 :

var source = new EventSource("serverSideEvents.php"); 
source.onmessage = function(event) { 
    var data = $.parseJSON(event.data); 
    $(data).each(function(){ 
      doSomethingWith(this); //works as expected 
     }); 
}; 

source.onerror = function(event) { 
    console.log(event); //fires every few seconds don't know why 
}; 

내 PHP는 :

<?php 
header('Content-Type: text/event-stream'); 
header('Cache-Control: no-cache'); 

    sendUpdates(); 

function sendUpdates() { 
    $controller = new someController(); 
    $out = $controller->Run(); 
    foreach($out as $msg) 
    sendSSEMessage($msg['id'], 'data:'.json_encode($msg)); 
} 

function sendSSEMessage($id, $data){ 
    echo "id: $id \n$data \n\n"; 
    ob_flush(); 
    flush(); 
} 

이는 CLI 또는 PHP는 오류가 발생하지 않습니다 브라우저, 아직 JS SSE의 오류 이벤트에, 확인 작업은 모든 시간을 발사 PHP가 실행됩니다. 콘솔에서 오류가 발생했습니다.

Event {isTrusted: true, type: "error", target: EventSource, currentTarget: EventSource, eventPhase: 2, …} 
bubbles:false 
cancelBubble:false 
cancelable:false 
composed:false 
currentTarget: 
EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …} 
defaultPrevented:false 
eventPhase:0 
isTrusted:true 
path:[] 
returnValue:true 
srcElement:EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …} 
target:EventSource {url: "http://localhost:7790/serverSideEvents.php", withCredentials: false, readyState: 0, onopen: null, onmessage: ƒ, …} 
timeStamp:1129162.5250000001 
type:"error" 
__proto__:Event 

명확한 내용 : 예상대로 작동합니다. 내가 필요한 서버 메시지를받습니다. 또한 오류 이벤트가 트리거됩니다.

+0

아마도 CORS 문제일까요? –

답변

0

그래, sitePoint 덕분에 알아 냈습니다. 오류 이벤트는 연결이 서버에 의해 닫힐 때마다 발생하며 스크립트가 종료 될 때마다 발생합니다. 그러면 브라우저가 다시 시도합니다.

그래서 우리는 php.ini에서 max_run_time에 따라 서버에 의해 종료되거나 결국 재실행의 정의 된 횟수 후에 자체적으로 종료함으로써 PHP를 유지해야합니다. 이렇게하면 브라우저를 다시 연결할 때 발생하는 오버 헤드를 줄일 수 있습니다. 그러나 스크립트를 실행 (잠자기 또는하지 않음)하면 서버로드에 부담이됩니다. 그래서 당신이 많은 연결이 있다면 이것은 바람직하지 않을 수 있습니다.

물론 오류를 무시할 수도 있습니다.

관련 문제