Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

javascript - How to stop Server-Sent Events

Hello I have a javascript code that listens to a PHP code via Server-Sent Events, it is working well the response is sent from the server trough a loop and when the loop ends the Server-Sent Events stops however a few seconds after the script is again listening. how can I end the Server-Sent Events when the loop from the server side ends too? Thanks.

JS :

var sse=new EventSource("data.php");
            sse.onmessage=function(event){
                document.getElementById("map").innerHTML+=event.data;              
            };

PHP:

<?php
header('Content-Type: text/event-stream'); //indicates that server is aware of server sent events
header('Cache-Control: no-cache');//disable caching of response

$coordinates = [  
   [  
      "20:11",
      33.5731235,
      -7.6433045
   ],
   [  
      "20:11",
      33.5731054,
      -7.6432876
   ],
   [  
      "20:11",
      33.5731644,
      -7.6433304
   ]
];

foreach($coordinates as $c){  
  echo "data: ".json_encode($c)."

";
  ob_get_flush();
  flush();
  sleep(1);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hi I've added extra to (hopefully fix this) You have to pass from the server a message to close the connection. Otherwise when the execution finishes the browser will start with a new connection

air code

JS :

var sse=new EventSource("data.php");
sse.onmessage=function(event){
    if ('END-OF-STREAM' == event.data) {
        sse.close(); // stop retry
    }
    document.getElementById("map").innerHTML+=event.data;
};

PHP:

<?php
header('Content-Type: text/event-stream'); //indicates that server is aware of server sent events
header('Cache-Control: no-cache');//disable caching of response

$coordinates = [
   [
      "20:11",
      33.5731235,
      -7.6433045
   ],
   [
      "20:11",
      33.5731054,
      -7.6432876
   ],
   [
      "20:11",
      33.5731644,
      -7.6433304
   ]
];

foreach($coordinates as $c){
    echo "data: ".json_encode($c)."

";
    ob_get_flush();
    flush();
    sleep( rand ( 1 , 3 ) );
}
echo "data: END-OF-STREAM

"; // Give browser a signal to stop re-opening connection
ob_get_flush();
flush();
sleep(1); // give browser enough time to close connection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...