Skip to content

Instantly share code, notes, and snippets.

@cpq
Last active June 1, 2018 17:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cpq/6225200 to your computer and use it in GitHub Desktop.
Save cpq/6225200 to your computer and use it in GitHub Desktop.
Example of mjpg streaming using mongoose web server.
// Copyright (c) 2013 Sergey Lyubka
// All rights reserved
//
// An example of mjpg streaming using mongoose web server.
// Usage:
// cc mjpg.c mongoose.c && ./a.out
// This code is public domain.
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include "mongoose.h"
static unsigned long get_file_size(const char *path) {
struct stat st;
return stat(path, &st) == 0 ? st.st_size : 0;
}
static void send_file_data(struct mg_connection *conn, const char *path) {
char buf[4 * 1024];
int n;
FILE *fp;
if ((fp = fopen(path, "rb")) != NULL) {
while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
mg_write(conn, buf, n);
}
fclose(fp);
}
}
static int begin_request_handler(struct mg_connection *conn) {
static const char *files[] = { "1.jpg", "2.jpg", "3.jpg", NULL };
int i;
mg_printf(conn, "%s",
"HTTP/1.0 200 OK\r\n" "Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\n"
"Connection: close\r\nContent-Type: multipart/x-mixed-replace; "
"boundary=--myboundary\r\n\r\n");
for (i = 0; files[i] != NULL; i++) {
mg_printf(conn, "--myboundary\r\nContent-Type: image/jpeg\r\n"
"Content-Length: %lu\r\n\r\n", get_file_size(files[i]));
send_file_data(conn, files[i]);
sleep(1);
}
return 1;
}
int main(void) {
static const char *options[] = {"listening_ports", "8080", NULL};
static struct mg_callbacks callbacks;
struct mg_context *ctx;
callbacks.begin_request = begin_request_handler;
ctx = mg_start(&callbacks, NULL, options);
getchar();
mg_stop(ctx);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment