Created
June 30, 2014 03:00
-
-
Save kazuho/be297f2735d836b3cd4f to your computer and use it in GitHub Desktop.
#libuv - only one of the callbacks is called when a socket which is at the same time reading / writing gets closed by peer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <uv.h> | |
static uv_tcp_t sconn, cconn; | |
static uv_connect_t cconn_ctx; | |
static uv_write_t wreq; | |
static uv_buf_t on_alloc(uv_handle_t *handle, size_t suggested_size) | |
{ | |
uv_buf_t ret; | |
ret.base = malloc(suggested_size); | |
ret.len = suggested_size; | |
return ret; | |
} | |
static void on_read(uv_stream_t *stream, ssize_t nread, uv_buf_t buf) | |
{ | |
printf("on_read:%d\n", (int)nread); | |
if (nread == -1) | |
uv_close((uv_handle_t*)stream, NULL); | |
} | |
static void on_write(uv_write_t *_wreq, int status) | |
{ | |
printf("on_write:%d\n", status); | |
if (status != 0) | |
uv_close((uv_handle_t*)&sconn, NULL); | |
} | |
static void on_accept(uv_stream_t *listener, int status) | |
{ | |
uv_buf_t wbuf; | |
if (status != 0) | |
return; | |
uv_tcp_init(listener->loop, &sconn); | |
if (uv_accept(listener, (uv_stream_t*)&sconn) != 0) | |
return; | |
//uv_read_start((uv_stream_t*)&sconn, on_alloc, on_read); | |
wbuf.base = malloc(16 * 1024 * 1024); | |
wbuf.len = 16 * 1024 * 1024; | |
uv_write(&wreq, (uv_stream_t*)&sconn, &wbuf, 1, on_write); | |
uv_read_start((uv_stream_t*)&sconn, on_alloc, on_read); | |
} | |
static void on_connect(uv_connect_t *req, int status) | |
{ | |
if (status != 0) | |
return; | |
uv_close((uv_handle_t*)&cconn, NULL); | |
} | |
int main(int argc, char **argv) | |
{ | |
uv_loop_t *loop = uv_default_loop(); | |
uv_tcp_t listener; | |
uv_tcp_init(loop, &listener); | |
uv_tcp_bind(&listener, uv_ip4_addr("127.0.0.1", 7890)); | |
uv_listen((uv_stream_t*)&listener, 128, on_accept); | |
uv_tcp_init(loop, &cconn); | |
uv_tcp_connect(&cconn_ctx, &cconn, uv_ip4_addr("127.0.0.1", 7890), on_connect); | |
return uv_run(loop, UV_RUN_DEFAULT); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment