使用mongoose创建双网络/套接字服务器

时间:2015-04-22 20:58:37

标签: c websocket webserver mongoose-web-server

我试图将我用Node.js,Express和Socket.io构建的示例移植到mongoose中 - 但是我无法让创建的服务器响应这两个WebSocket连接和通用HTTP请求。

我首先从mongoose复制web_server示例,它只是创建一个HTTP服务器。在此示例中,行384调用mg_create_server(NULL, EV_HANDLER),其中EV_HANDLER实际上为NULL - 因此对服务器的所有HTTP请求都恰好映射到" document_root"正如你所料。 到目前为止,非常好。

但是,当我查看随mongoose一起提供的各种WebSocket示例时,我看到mg_create_server(server, handler)调用定义了一个实际的处理程序方法 - 类似这样:

static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
    switch (ev) {
        case MG_REQUEST:
            if (conn->is_websocket) {
                handle_websocket_message(conn);
                return MG_TRUE;
            } 
            else {
                mg_send_file(conn, "index.html", NULL);  // Return MG_MORE after!
                return MG_MORE;
            }
        case MG_WS_CONNECT:
            // New websocket connection. Send connection ID back to the client.
          conn->connection_param = calloc(1, sizeof(struct conn_data));
          mg_websocket_printf(conn, WEBSOCKET_OPCODE_TEXT, "id %p", conn);
          return MG_FALSE;
        case MG_CLOSE:
            free(conn->connection_param);
            return MG_TRUE;
        case MG_AUTH:
            return MG_TRUE;
        default:
            return MG_FALSE;
    }
}

在这些示例中,MG_REQUEST案例手动返回" index.html"对于任何请求,它不是来自WebSocket ......对于简单的示例很有用,但它并不能帮助我理解如何在同一台服务器上托管网站和套接字连接。 / p>

我尝试将ev_handler方法从WebSocket示例移植到" web_server"例如,但HTTP请求似乎只是挂起而永远不会解决。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

有几种方法可以解决这个问题:

  1. 修复您的示例。改变这个

    mg_send_file(conn, "index.html", NULL);
    return MG_MORE;
    

    到这个

    return MG_FALSE;
    

    不要忘记设置“document_root”选项。

  2. 使用窝 - 这是同一供应商(Cesanta)的图书馆。 Fossa是Mongoose的超集,具有更丰富,更清晰的API。 Fossa对普通HTTP和Websocket请求使用不同的事件。以下是一个示例:https://github.com/cesanta/fossa/blob/master/examples/websocket_chat/websocket_chat.c