I wanted to create multithreading mjpeg streaming in c++, and I succeded with single thread, but when I try to start the "stream" function in a separate thread or using std::async (I thought async was better than create a thread in this case), I don't understand why, it doesn't work. That function, seems not to start in other thread. Please can you help me? Thanks
streamer.cpp
#include "streamer.h"
#include <cstring>
#include <sys/types.h>
#include <unistd.h>
#include <future>
void Streamer::stream(int socket)
{
std::string image, buffer;
int check = send(socket, header.c_str(), header.size(), MSG_NOSIGNAL);
while (check > 0)
{
image = camera->getFrameInByteArray();
buffer = "--boundary\r\n"
"Content-Type: image/jpeg\r\n"
"Content-Length: " + std::to_string(image.size()) + "\r\n\r\n" + image;
check = send(socket, buffer.c_str(), buffer.size(), MSG_NOSIGNAL);
}
close(socket);
}
void Streamer::start() {
bindChannel();
listen(socketFileDescriptor, 5);
socklen_t clientLenght = sizeof(clientAddress);
while(1) {
newSocketFileDescriptor = accept(socketFileDescriptor, (struct sockaddr *) &clientAddress, &clientLenght);
if (newSocketFileDescriptor < 0)
error("Error accepting request");
/*If I do this, I can't serve more than one request*/
std::async(std::launch::async, &Streamer::stream, this, newSocketFileDescriptor);
}
close(socketFileDescriptor);
}
void Streamer::error(std::string msg){...}
void Streamer::bindChannel(){...}
Streamer::~Streamer(){...}
Streamer::Streamer(int port, int cameraAddress){...}
EDIT:
I tried to define as static and modify stream() function in this way:
void Streamer::stream(Camera &cam, int socket)
{
std::string head = "HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Max-Age: 0\r\n"
"Expires: 0\r\n"
"Cache-Control: no-cache, private\r\n"
"Pragma: no-cache\r\n"
"Content-Type: multipart/x-mixed-replace;boundary=--boundary\r\n\r\n";
std::string image, buffer;
int check = send(socket, head.c_str(), head.size(), MSG_NOSIGNAL);
while (check > 0)
{
image = cam.getFrameInByteArray();
buffer = "--boundary\r\n"
"Content-Type: image/jpeg\r\n"
"Content-Length: " + std::to_string(image.size()) + "\r\n\r\n" + image;
check = send(socket, buffer.c_str(), buffer.size(), MSG_NOSIGNAL);
}
close(socket);
}
and I tried these:
//std::thread{Streamer::stream, std::ref(*camera), newSocketFileDescriptor}.detach();
//auto f = std::async(std::launch::async, Streamer::stream, std::ref(*camera), newSocketFileDescriptor);
//std::async(std::launch::async, Streamer::stream, std::ref(*camera), newSocketFileDescriptor);
In all cases I can serve only one request at a time