Created
September 2, 2016 14:39
-
-
Save bagder/c30e00e4f9839eec452069fb47955a99 to your computer and use it in GitHub Desktop.
This file contains 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 <uv.h> | |
static void on_close(uv_handle_t* handle); | |
static void on_connect(uv_connect_t* req, int status); | |
static void on_write(uv_write_t* req, int status); | |
static void on_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) | |
{ | |
void *ptr; | |
printf("on_alloc\n"); | |
ptr = malloc(suggested_size); | |
buf->base = ptr; | |
buf->len = suggested_size; | |
} | |
static void on_close(uv_handle_t* handle) | |
{ | |
printf("on_close\n"); | |
} | |
static void on_write(uv_write_t* req, int status) | |
{ | |
printf("on_write\n", status); | |
} | |
static void on_read(uv_stream_t *tcp, ssize_t nread, const uv_buf_t *buf) | |
{ | |
if(nread > 0) { | |
printf("on_read\n"); | |
fwrite(buf->base, nread, 1, stdout); | |
} | |
else { | |
/* EOF */ | |
uv_close((uv_handle_t*)tcp, on_close); | |
} | |
free(buf->base); | |
} | |
static void on_connect(uv_connect_t* connection, int status) | |
{ | |
uv_stream_t *stream = connection->handle; | |
uv_write_t request; | |
uv_buf_t http = { | |
.base = "GET / HTTP/1.0\r\n\r\n", | |
.len = 18, | |
}; | |
printf("connected.\n"); | |
uv_write(&request, stream, &http, 1, on_write); | |
uv_read_start(stream, on_alloc, on_read); | |
} | |
int main(int argc, char **argv) | |
{ | |
uv_loop_t *loop = uv_default_loop(); | |
uv_tcp_t socket; | |
struct sockaddr_in addr; | |
uv_connect_t connect; | |
uv_tcp_init(loop, &socket); | |
uv_tcp_keepalive(&socket, 1, 60); | |
uv_ip4_addr("127.0.0.1", 80, &addr); | |
uv_tcp_connect(&connect, &socket, (const struct sockaddr *) &addr, on_connect); | |
uv_run(loop, UV_RUN_DEFAULT); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are allocating the uv_write_t on the stack, but it must remain valid until the write callback is called, otherwise bad things will happen.