具有两个客户端的简单libuv服务器在第二个客户端连接后继续在循环中调用写回调

时间:2016-03-06 17:30:05

标签: libuv

我正在玩libuv而我正在尝试使用一个简单的服务器来监听localhost,每当客户端连接时,只需发送一个“Hello”。

问题是,服务器似乎工作正常,但是在第一次连接之后,写回调一直在循环中被调用,永远不要放手。

这是一个完整的代码示例。出了什么问题?

#include <iostream>
#include <uv.h>

class Server
{
public:
Server() : m_connectionCount(0)
{
    struct sockaddr_in addr;

    int status = uv_tcp_init(uv_default_loop(), &m_socket);
    if(status)
    {
        exit(1);
    }

    uv_ip4_addr("0.0.0.0", 8888, &addr);

    status = uv_tcp_bind(&m_socket, (const struct sockaddr*) &addr, 0);
    if (status)
    {
        exit(1);
    }

    m_socket.data = this;

    status = uv_listen((uv_stream_t*)&m_socket, 128, [](uv_stream_t* server, int status)
    {
        Server* pServer = (Server*)server->data;
        if(pServer->m_connectionCount >= 2)
            return;

        uv_tcp_t* client = &(pServer->m_connections[pServer->m_connectionCount]);
        int error = uv_tcp_init(uv_default_loop(), client);
        if(error)
            exit(1);

        client->data = pServer;

        error = uv_accept(server, (uv_stream_t*)client);
        if(error)
            exit(1);

        auto allocate = [](uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf)
        {
            buf->base = (char*)malloc(suggested_size);
            buf->len = suggested_size;
        };

        auto onRead = [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
        {
        };

        error = uv_read_start((uv_stream_t*)client, allocate, onRead);
        if(error)
            return;

        pServer->m_connectionCount++;
        for(size_t i=0; i<pServer->m_connectionCount; ++i)
        {
            uv_stream_t* stream = (uv_stream_t*)&(pServer->m_connections[i]);

            uv_buf_t buffer = {.len = 6, .base = "Hello"};
            uv_write_t req;
            uv_write(&req, stream, &buffer, 1,
                     [](uv_write_t* request, int status)
                     {
                         /*** PROBLEM: After the second client connects this keeps getting called in a loop ... ?***/
                         printf("Write completed\n");
                     });

        }
    });

    if (status)
    {
        exit(1);
    }

    uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}

private:
     uv_tcp_t m_socket;
     uv_tcp_t m_connections[2];
     uint32_t m_connectionCount;
};

int main(int argc, const char * argv[])
{
    Server testServer;
}

P.S。永远不要泄漏泄漏等等,这只是为了说明写回调问题。

1 个答案:

答案 0 :(得分:0)

我明白了。问题是循环中的uv_write_t需要动态分配,这样当它超出范围时就不会被删除。我(错误地)假设请求被复制。

奇怪的是,缓冲结构似乎不需要动态分配。

如果其他人遇到问题则发布此信息