cURL - Structuring request to validate server sent events
For completeness, your curl command should look something like this:
$ curl -N --http2 -H "Accept:text/event-stream" https://some.address.com/clocktimes
The -N
argument is very important, because curl buffers the response. So it's possible that your server will have sent some data, but it's not rendered on the screen because of curl buffering. Anytime you use curl for streaming, you should include this flag.
The -H
should be included as best practice because if your server has bound other protocols to the same port, it won't be able to disambiguate the protocol.
For example, if port 443 is used for HTTPS and SSE, then you will need to provide the -H
header so the server knows this is an SSE request.
The example above assumes the server is using HTTP/2. If not, drop the --http2
argument and change the scheme from https://
to http://
SSE is a text-based protocol, and curl is a great way to troubleshoot exactly what your connection is sending. The command is this simple:
curl -N http://127.0.0.1/path/to/clock.php
(The -N
stops any buffering, so data is shown as it is received.)
And it outputs this:
data:2015-07-07 06:19:27
data:2015-07-07 06:19:28
data:2015-07-07 06:19:29
data:2015-07-07 06:19:30
data:2015-07-07 06:19:31
data:2015-07-07 06:19:32
Notice how it shows the "data:" prefix of the SSE protocol, and also clearly shows the double LFs. It runs forever, until you press ctrl-c.
About the only thing to point out is that you must use a web server; you cannot run SSE over the file:// protocol.
For more hard-core troubleshooting, add --verbose
, which will show the headers being sent, and the headers being received.
SSE does support cookies, which you could give like this: (you would first have to prepare the "cookies.txt" file):
curl -N --cookie cookies.txt http://127.0.0.1/path/to/clock.php
See other answer and the curl documentation for other options you might want to consider using. If you are troubleshooting problems in a specific browser, use their devtools to find out exactly what headers are being sent, and then you can tell curl up to do the same.
For completeness, here is the clock.php script:
<?php
set_time_limit(0);
header("Content-type: text/event-stream");
while(1){
echo "data:" . date("Y-m-d H:i:s") . "\n\n";
@ob_flush();flush();
sleep(1);
}