I'm writing a program whose task is communication between the client and the server. the point is that the server runs in the background, and after starting the second program, the client connects via TCP and then sends it a message. At the moment, analyzing the data collected by wireshark, I can say that I manage to establish a connection and send a packet with a message, the problem occurs when the server receives the message, the "on_read" function is not called. Server code:
#include <uv.h>
#include <iostream>
void on_read(uv_stream_t* client, ssize_t nread, const uv_buf_t* buf)
{
std::cout << "ANY DATA?\n";
if(nread > 0)
{
std::cout << "Received: " << std::string(buf->base, nread) << std::endl;
}
else if(nread < 0)
{
uv_close((uv_handle_t*)client, NULL);
}
free(buf->base);
}
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;
}
void on_new_connection(uv_stream_t* server, int status)
{
if(status < 0)
{
std::cerr << "Error on_new_connection: " << uv_strerror(status) << std::endl;
return;
}
uv_tcp_t* client = new uv_tcp_t();
uv_tcp_init(uv_default_loop(), client);
if(uv_accept(server, (uv_stream_t*)client) < 0)
{
uv_close((uv_handle_t*)client, NULL);
return;
}
std::cout << "New connection accepted." << std::endl;
uv_read_start((uv_stream_t*)&client, alloc_buffer, on_read);
}
int main()
{
uv_tcp_t server;
uv_tcp_init(uv_default_loop(), &server);
struct sockaddr_in bind_addr;
uv_ip4_addr("0.0.0.0", 7000, &bind_addr);
if(int r = uv_tcp_bind(&server, (const struct sockaddr*)&bind_addr, 0); r < 0)
{
std::cerr << "Error binding server: " << uv_strerror(r) << std::endl;
return 1;
}
if(int r = uv_listen((uv_stream_t*)&server, 128, on_new_connection); r < 0)
{
std::cerr << "Error starting server: " << uv_strerror(r) << std::endl;
return 1;
}
std::cout << "Server started on port 7000." << std::endl;
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
return 0;
}
client code:
#include <uv.h>
#include <iostream>
void after_send(uv_write_t *req, int status)
{
std::cout << status << "as\n";
}
void on_connect(uv_connect_t* req, int status)
{
if(status < 0)
{
std::cerr << "Error on_connect: " << uv_strerror(status) << std::endl;
return;
}
std::cout << "Connected to server." << std::endl;
Sleep(1000);
uv_buf_t buf = uv_buf_init("Hello, server!\r\n", 14);
uv_write_t write_req;
uv_write(&write_req, req->handle, &buf, 1, after_send);
}
int main()
{
uv_tcp_t client;
uv_tcp_init(uv_default_loop(), &client);
struct sockaddr_in serv_addr;
uv_ip4_addr("127.0.0.1", 7000, &serv_addr);
uv_connect_t connect_req;
uv_tcp_connect(&connect_req, &client, (const struct sockaddr*)&serv_addr, on_connect);
return uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
I want the server to display this message on the screen after the client sends a message