Created
September 8, 2016 08:19
-
-
Save bagder/ffb613e3c3c5f41813b31fc09ef1c261 to your computer and use it in GitHub Desktop.
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 <poll.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; | |
} | |
/* global for simplicity */ | |
int streams_going = 1; | |
static void on_close(uv_handle_t* handle) | |
{ | |
printf("on_close\n"); | |
streams_going--; | |
} | |
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 /512M HTTP/1.0\r\n\r\n", | |
.len = 22, | |
}; | |
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; | |
int backend_fd; | |
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); | |
backend_fd = uv_backend_fd(loop); | |
/* kick off the event loop first */ | |
uv_run(loop, UV_RUN_NOWAIT); | |
while (streams_going) { | |
struct pollfd fds[1] = { | |
{ | |
.fd = backend_fd, | |
.events = POLLERR | POLLIN | POLLHUP, | |
.revents = 0, | |
} | |
}; | |
int rc = poll(fds, 1, 1000); | |
if (rc > 0) { | |
/* there's stuff to do */ | |
uv_run(loop, UV_RUN_NOWAIT); | |
} | |
else { | |
fprintf(stderr, "Waiting on %d streams...\n", streams_going); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment