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

// 回调函数，用于处理从客户端接收到的数据
void echo_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
    if (nread < 0) {
        std::cerr << "Read error: " << uv_strerror(nread) << std::endl;
        uv_close((uv_handle_t*)stream, nullptr);
        free(buf->base);
        return;
    }

    if (nread > 0) {
        // 打印接收到的数据
        std::cout << "Received: " << std::string(buf->base, nread) << std::endl;
    }

    // 释放缓冲区
    free(buf->base);
}

// 回调函数，用于处理新的客户端连接
void on_connection(uv_stream_t* server, int status) {
    if (status < 0) {
        std::cerr << "Connection error: " << uv_strerror(status) << std::endl;
        return;
    }

    uv_tcp_t* client = new uv_tcp_t;
    uv_tcp_init(server->loop, client);

    if (uv_accept(server, (uv_stream_t*)client) == 0) {
        uv_read_start((uv_stream_t*)client, [](uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
            buf->base = (char*)malloc(suggested_size);
            buf->len = suggested_size;
        }, echo_read);
    } else {
        uv_close((uv_handle_t*)client, nullptr);
    }
}

int main() {
    uv_loop_t* loop = uv_default_loop();
    uv_tcp_t server;
    uv_tcp_init(loop, &server);

    struct sockaddr_in bind_addr;
    uv_ip4_addr("0.0.0.0", 8098, &bind_addr);

    uv_tcp_bind(&server, (const struct sockaddr*)&bind_addr, 0);
    uv_listen((uv_stream_t*)&server, 128, on_connection);

    std::cout << "Server listening on port 8098" << std::endl;
    uv_run(loop, UV_RUN_DEFAULT);

    return 0;
}