0

I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include "uv.h"

int64_t counter = 0;

void on_new_connection(uv_stream_t *server, int status);

int main(void)
{
    uv_tcp_t server;
    uv_tcp_init(uv_default_loop(), &server);

    struct sockaddr_in socket;

    uv_ip4_addr("127.0.0.1", 7000, &socket);
    uv_tcp_bind(&server, (struct sockaddr *) &socket, 42);
    int r = uv_listen((uv_stream_t*) &server, 128,
            on_new_connection);
    if (r) {
        fprintf(stderr, "Listen error\n");
        return 1;
    }

    return uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}

void on_new_connection(uv_stream_t *server, int status)
{
    printf("new connection\n");

    if (status == -1) {
        return;
    }

    uv_tcp_t *client = malloc(sizeof(uv_tcp_t));
    uv_tcp_init(uv_default_loop(), client);
//  if (uv_accept(server, (uv_stream_t*) client) == 0) {
//      uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
//  }
//  else {
//      uv_close((uv_handle_t*) client, NULL);
//  }
}

I just want to start this server and connecting (via telnet or a browser) to this server. Everything seems ok except that the first connection always print the "new connection" string in the on_new_connection but any new telnet sessions that I start don't print new connection. What am I missing? it seems that the on_new_connection callback is called only once, why?

amurdaca
  • 57
  • 1
  • 5

3 Answers3

1

Why did you comment out the code with the call to uv_accept()? In a connection callback, the user has to call uv_accept() to accept the pending connection. The server i/o watcher is then resumed after this call. In your case, the watcher doesn't get resumed. That's why you observe a single callback.

neoxic
  • 535
  • 3
  • 12
0

Possibly, you are not specifying the correct port with telnet?

telnet 127.0.0.1 7000

pughar
  • 148
  • 1
  • 6
0

You're also not checking the status value. You always get the callback, but you don't know if it's an error of some sort

Mark Nunberg
  • 3,551
  • 15
  • 18