test: add udp4_echo_server helper

This commit is contained in:
Ben Noordhuis 2012-01-13 19:15:50 +01:00
parent a13584bec7
commit dc3b80a50f
3 changed files with 66 additions and 0 deletions

View File

@ -34,6 +34,7 @@ static uv_loop_t* loop;
static int server_closed;
static stream_type serverType;
static uv_tcp_t tcpServer;
static uv_udp_t udpServer;
static uv_pipe_t pipeServer;
static uv_handle_t* server;
@ -176,6 +177,34 @@ static void on_server_close(uv_handle_t* handle) {
}
static void on_send(uv_udp_send_t* req, int status);
static void on_recv(uv_udp_t* handle,
ssize_t nread,
uv_buf_t buf,
struct sockaddr* addr,
unsigned flags) {
uv_udp_send_t* req;
int r;
ASSERT(nread > 0);
ASSERT(addr->sa_family == AF_INET);
req = malloc(sizeof(*req));
ASSERT(req != NULL);
r = uv_udp_send(req, handle, &buf, 1, *(struct sockaddr_in*)addr, on_send);
ASSERT(r == 0);
}
static void on_send(uv_udp_send_t* req, int status) {
ASSERT(status == 0);
free(req);
}
static int tcp4_echo_start(int port) {
struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", port);
int r;
@ -242,6 +271,30 @@ static int tcp6_echo_start(int port) {
}
static int udp4_echo_start(int port) {
int r;
server = (uv_handle_t*)&udpServer;
serverType = UDP;
r = uv_udp_init(loop, &udpServer);
if (r) {
fprintf(stderr, "uv_udp_init: %s\n",
uv_strerror(uv_last_error(loop)));
return 1;
}
r = uv_udp_recv_start(&udpServer, echo_alloc, on_recv);
if (r) {
fprintf(stderr, "uv_udp_recv_start: %s\n",
uv_strerror(uv_last_error(loop)));
return 1;
}
return 0;
}
static int pipe_echo_start(char* pipeName) {
int r;
@ -304,3 +357,14 @@ HELPER_IMPL(pipe_echo_server) {
uv_run(loop);
return 0;
}
HELPER_IMPL(udp4_echo_server) {
loop = uv_default_loop();
if (udp4_echo_start(TEST_PORT))
return 1;
uv_run(loop);
return 0;
}

View File

@ -42,6 +42,7 @@
typedef enum {
TCP = 0,
UDP,
PIPE
} stream_type;

View File

@ -128,6 +128,7 @@ TEST_DECLARE (listen_no_simultaneous_accepts)
#endif
HELPER_DECLARE (tcp4_echo_server)
HELPER_DECLARE (tcp6_echo_server)
HELPER_DECLARE (udp4_echo_server)
HELPER_DECLARE (pipe_echo_server)