mongoose tcp发送文件 server端

#include "mongoose.h"
#include <sstream>
#include <string>
#include <thread>
using namespace std;
string cookie;
struct mg_mgr mgr;
FILE *fp= nullptr;
union
{
    int len = 0;
    char strlen[4];
} per_data;
int m=0;
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
    struct mbuf *io = &nc->recv_mbuf;
    switch (ev) {
        case MG_EV_RECV:
        {
            memcpy(per_data.strlen,io->buf,4);
            mbuf_remove(io, 4);
            string json(io->buf,io->len);
            printf("rec  %s\n",json.c_str());
            //收到新数据并将其附加到recv_mbuf ,
//      string fileName("D:/IMG/video/c.mp4");

//            FILE *fp = fopen("D:/IMG/video/a.jpg","rb");
            fp = fopen("D:/IMG/video/c.mp4","rb");
            if(!fp) return ;
            fseek(fp,0,SEEK_END);
            long size=ftell(fp);
            fseek(fp,0,SEEK_SET);

            string str=("{\"Msg\":0,\"len\":");
            str.append(to_string(size));
            str.append(",\"code\":1,\"fileName\":\"D:/IMG/data/a");
            str.append(to_string(m++));
            str.append(".mp4\"}");
            int len=str.length();
            mg_send(nc, &len, 4);
            mg_send(nc,str.c_str(), str.length());
            printf("sen %s\n",str.c_str());
            char buf[BUFSIZ];
            size_t n;
            while ((n = fread(buf, 1, BUFSIZ, fp)) > 0) {
                mg_send(nc, buf, n);
            }
            fclose(fp);
            mbuf_remove(io, io->len);

            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        }
            break;
        default:
            break;
    }
}

bool flag=true;
void  main(int argc, char *argv[]){

    mg_mgr_init(&mgr, nullptr);
    mg_bind(&mgr, "tcp://127.0.0.1:18888", ev_handler);
    while(flag){
        mg_mgr_poll(&mgr, 10);
    }
    mg_mgr_free(&mgr);
}

猜你喜欢

转载自blog.csdn.net/douzi949389/article/details/80110456