Simple example showing a basic SSE (Server-sent events) server.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
#define PAGE \
"<html>\n" \
"<head>\n" \
"<title>SSE example</title>\n" \
"</head><body><h2 id=\"counter\">Please wait ...</h2>\n" \
"<script>\n" \
"const es = new EventSource('/');\n" \
"es.onmessage = function (ev) {\n" \
" document.getElementById('counter').innerText = 'Counting: ' + ev.data;\n" \
"};\n" \
"</script>\n" \
"</body>\n" \
"</html>"
static unsigned int COUNT = 0;
#ifdef _WIN32
#define sleep Sleep
#endif
static ssize_t sse_read_cb(__SG_UNUSED void *handle, uint64_t offset, char *buf,
size_t size) {
char msg[20];
if (offset == 0) {
size = sprintf(msg, "retry: 1000\n");
} else {
size = sprintf(msg, "data: %d\n\n", ++COUNT);
sleep(1);
}
memcpy(buf, msg, size);
msg[size] = '\0';
return size;
}
static void req_cb(__SG_UNUSED
void *cls,
struct sg_httpreq *req,
return;
}
return;
}
}
int main(int argc, const char *argv[]) {
if (argc != 2) {
printf("%s <PORT>\n", argv[0]);
return EXIT_FAILURE;
}
return EXIT_FAILURE;
}
fprintf(stdout, "Server running at http://localhost:%d\n",
fflush(stdout);
getchar();
return EXIT_SUCCESS;
}
struct sg_strmap ** sg_httpres_headers(struct sg_httpres *res)
struct sg_httpsrv * sg_httpsrv_new(sg_httpreq_cb cb, void *cls) __attribute__((malloc))
struct sg_strmap ** sg_httpreq_headers(struct sg_httpreq *req)
void sg_httpsrv_free(struct sg_httpsrv *srv)
const char * sg_httpreq_path(struct sg_httpreq *req)
int sg_httpres_sendstream(struct sg_httpres *res, uint64_t size, sg_read_cb read_cb, void *handle, sg_free_cb free_cb, unsigned int status)
#define sg_httpres_send(res, val, content_type, status)
Definition sagui.h:1032
bool sg_httpsrv_listen(struct sg_httpsrv *srv, uint16_t port, bool threaded)
uint16_t sg_httpsrv_port(struct sg_httpsrv *srv)
int sg_strmap_set(struct sg_strmap **map, const char *name, const char *val)
const char * sg_strmap_val(struct sg_strmap *pair)
int sg_strmap_find(struct sg_strmap *map, const char *name, struct sg_strmap **pair)