Libuv TCPP客户端

当你在服务器端完成绑定/监听/接收的操作后,在客户端只要简单地调用uv_tcp_connect,它的回调函数和上面类似,具体例子如下:

uv_tcp_t* socket = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
uv_tcp_init(loop, socket);

uv_connect_t* connect = (uv_connect_t*)malloc(sizeof(uv_connect_t));

struct sockaddr_in dest;
uv_ip4_addr("127.0.0.1", 80, &dest);

uv_tcp_connect(connect, socket, dest, on_connect);

当建立连接后,回调函数on_connect会被调用。回调函数会接收到一个uv_connect_t结构的数据,它的handle指向通信的socket。

libuv代码示例

如我们需要连接上服务器,给服务器发送一段数据后,再接收一段数据后,关闭网络。

// libuv-server.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"uv.h"

#pragma comment(lib,"libuv.lib")
#pragma comment(lib,"Ws2_32.lib")
#pragma comment(lib,"iphlpapi.lib")
#pragma comment(lib,"Userenv.lib")
#pragma comment(lib,"Psapi.lib")

void close_cb(uv_handle_t* handle)
{
}
void alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf)
{
    buf->base = (char*)malloc(suggested_size);
    buf->len = suggested_size;


}


typedef struct
{
    uv_write_t req;
    uv_buf_t buf;
}write_req_t;



uv_tcp_t* sk = NULL;

void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
{
    if (nread > 0)
    {
        buf->base[nread] = '\0';
        printf("%s\n", buf->base);
    }

    if (buf->base != NULL)
    {
        free(buf->base);
    }

    //关闭
    uv_close((uv_handle_t*)sk, close_cb);
}

void echo_write(uv_write_t* req, int status)
{
    if (status)
    {
        fprintf(stderr, "Write error %s\n", uv_strerror(status));
        return;
    }

    write_req_t *wr = (write_req_t*)req;
    free(wr->buf.base);
    free(wr);
}






void  on_connect(uv_connect_t* req, int status)
{
    if (status < 0)
    {
        return;
    }

    write_req_t *wq = (write_req_t *)malloc(sizeof(write_req_t));
    wq->buf.base = (char*)malloc(sizeof(write_req_t));
    wq->buf.len = strlen("clent to server") + 1;
    memcpy(wq->buf.base, "clent to server", strlen("clent to server")+1);
    uv_write((uv_write_t *)wq, req->handle, &wq->buf, 1, echo_write);

    uv_read_start((uv_stream_t*)req->handle, alloc_buffer, read_cb);
}

int _tmain(int argc, _TCHAR* argv[])
{
    uv_loop_t* loop = uv_default_loop();
    sk = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
    uv_tcp_init(loop, sk);

    uv_connect_t* connect = (uv_connect_t*)malloc(sizeof(uv_connect_t));

    struct sockaddr_in dest;
    uv_ip4_addr("127.0.0.1", 3333, &dest);

    int r = uv_tcp_connect(connect, sk, (struct sockaddr*)&dest, on_connect);
    if (r)
    {
        fprintf(stderr, "Listen error %s\n", uv_strerror(r));
        return 1;
    }



    return uv_run(loop, UV_RUN_DEFAULT);
}