diff --git a/Makefile b/Makefile index a1c0e28..f644343 100644 --- a/Makefile +++ b/Makefile @@ -1,2 +1,2 @@ camera_stream: *.c *.h - gcc -g -o camera_stream *.c \ No newline at end of file + gcc -g -lpthread -o camera_stream *.c \ No newline at end of file diff --git a/http.c b/http.c new file mode 100644 index 0000000..a9532b1 --- /dev/null +++ b/http.c @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "http.h" + +#define BUFSIZE 256 + +int http_listen(int listen_port, int maxcons) +{ + struct sockaddr_in server = {0}; + int listenfd = -1; + + // getaddrinfo for host + server.sin_family = AF_INET; + server.sin_addr.s_addr = INADDR_ANY; + server.sin_port = htons(listen_port); + + listenfd = socket(AF_INET, SOCK_STREAM, 0); + if (listenfd < 0) { + return -1; + } + + if (bind(listenfd, (struct sockaddr *)&server, sizeof(server)) < 0) { + goto error; + } + + if (listen(listenfd, maxcons) < 0) { + goto error; + } + + return listenfd; +error: + if (listenfd >= 0) + close(listenfd); + return -1; +} + +void http_process(int fd, struct sockaddr_in *addr) +{ + FILE *stream = fdopen(fd, "r+"); + if (!stream) { + return; + } + + char line[BUFSIZE]; + fgets(line, BUFSIZE, stream); + + fprintf(stream, "HTTP/1.1 200 OK\n"); + fprintf(stream, "Content-Type: text/plain\n"); + fprintf(stream, "\r\n"); + fprintf(stream, "Text.\n"); + fflush(stream); + fclose(stream); +} + +int http_worker(int listenfd) +{ + while (1) { + struct sockaddr_in addr; + int addrlen = sizeof(addr); + int ret = accept(listenfd, (struct sockaddr *)&addr, &addrlen); + if (ret < 0) { + return -1; + } + + http_process(ret, &addr); + close(ret); + } + + return -1; +} + +int http_worker_threads(int listenfd, int nthreads) +{ + while (nthreads-- > 0) { + pthread_t thread; + pthread_create(&thread, NULL, (void *(*)(void*))http_worker, (void*)listenfd); + } + + return 0; +} diff --git a/http.h b/http.h new file mode 100644 index 0000000..de7500e --- /dev/null +++ b/http.h @@ -0,0 +1,7 @@ +#pragma once + +#include "v4l2.h" + +int http_listen(int listen_port, int maxcons); +int http_worker(int listenfd); +int http_worker_threads(int listenfd, int nthreads); diff --git a/main.c b/main.c index 89a442c..a215065 100644 --- a/main.c +++ b/main.c @@ -3,6 +3,7 @@ #include "device.h" #include "links.h" #include "v4l2.h" +#include "http.h" int camera_width = 1920; int camera_height = 1080; @@ -103,6 +104,11 @@ int main(int argc, char *argv[]) // return -1; // } + int httpfd = http_listen(9090, 5); + if (httpfd >= 0) { + http_worker_threads(httpfd, 8); + } + bool running = false; links_loop(links, &running); diff --git a/v4l2.h b/v4l2.h index 6f864bd..f473af9 100644 --- a/v4l2.h +++ b/v4l2.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include