猫鼬网络响应延迟

时间:2015-12-12 14:12:35

标签: c++ mongoose-web-server

我是mongoose web服务器的新手。我正在开发一个简单的http服务器,它返回一个图像作为响应,一切正常。但是当从浏览器请求时,不管文件大小如何,到达Web服务器事件处理程序只需要1000毫秒。 是否有任何配置可以改变这种延迟。

static const char *s_http_port = "8089";
static struct mg_serve_http_opts s_http_serve_opts;

static void send_file(struct mg_connection *nc){
    char buf[1024];
    int n;
    FILE *fp;
    const char *file_path = "C:\\sample.jpg";
    fp = fopen(file_path, "rb");
    if(fp == NULL){
        printf("Error, file %s not found.", file_path);
    }
    char *mimeType = "image/jpg";
    fseek(fp, 0L, SEEK_END);
    long sz = ftell(fp) + 2;
    fseek(fp, 0L, SEEK_SET);
    mg_printf(nc,
                    "HTTP/1.1 200 OK\r\n"
                    "Cache: no-cache\r\n"
                    "Content-Type: %s\r\n"
                    "Content-Length: %d\r\n"
                    "\r\n",
                    mimeType,
                    sz);
    while((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
        mg_send(nc, buf, n);
    }
    fclose(fp);
    mg_send(nc, "\r\n", 2);
    nc->flags |= MG_F_SEND_AND_CLOSE;
}
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data){
    struct http_message *hm = (struct http_message *)ev_data;
    switch(ev)
    {
    case MG_EV_HTTP_REQUEST:
        {
            if(mg_vcmp(&hm->uri, "/hello") == 0){
                handle_recv(nc);
            } else if(mg_vcmp(&hm->uri, "/img") == 0){
                send_file(nc);
            } else {
                mg_serve_http(nc, (struct http_message *) ev_data, s_http_serve_opts);
            }
        }
        break;
    case MG_EV_RECV:
        break;
    case MG_EV_CLOSE:
        break;
    }
}

int main(void)
{
    struct mg_mgr mgr;
    struct mg_connection *nc;
    mg_mgr_init(&mgr, NULL);
    nc = mg_bind(&mgr, s_http_port, ev_handler);
    mg_set_protocol_http_websocket(nc);
    s_http_serve_opts.document_root = "./images";
    s_http_serve_opts.dav_document_root = "./images";
    s_http_serve_opts.enable_directory_listing = "yes";
    printf("Starting web server on port %s\n", s_http_port);
    for(;;) {
        mg_mgr_poll(&mgr, 500);
    }
    mg_mgr_free(&mgr);
    return 0;
}

0 个答案:

没有答案