I am new to cURL and server sent events. I know how to build a simple GET
, POST
requests using cURL and getting response. Also, theoretically I am aware that server sent events are handled by creating a listener to event source but I am not sure how to proceed with validating any such API with cURL. Any guidance is appreciated.
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);
}
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://
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With