Skip to content

Instantly share code, notes, and snippets.

@strax
Created June 12, 2011 16:31
Show Gist options
  • Save strax/1021735 to your computer and use it in GitHub Desktop.
Save strax/1021735 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "uv/uv.h"
static uv_tcp_t server;
void on_close(uv_handle_t* handle) {
// release the handle
free(handle);
printf("disconnected\n");
}
uv_buf_t on_alloc(uv_tcp_t* handle, size_t suggested_size) {
printf("allocating, suggested size is %d bytes\n", (int)suggested_size);
uv_buf_t buf;
buf.base = malloc(suggested_size);
buf.len = suggested_size;
return buf;
}
void on_read(uv_tcp_t* handle, ssize_t nread, uv_buf_t buf) {
printf("reading\n");
if(nread > 0) {
write(1, buf.base, nread);
} else {
// ?
}
free(buf.base);
}
void on_connection(uv_tcp_t* server_handle, int status) {
printf("connected\n");
uv_tcp_t *client;
uv_tcp_init(client);
printf("client initialised\n");
int r = uv_accept(server_handle, client);
if(r) {
uv_err_t err = uv_last_error();
fprintf(stderr, "accept: %s\n", uv_strerror(err));
return;
}
printf("client accepted\n");
// uv_read_start(client, on_alloc, on_read);
uv_close((uv_handle_t*)client, on_close);
}
int main() {
uv_init();
uv_tcp_init(&server);
struct sockaddr_in address = uv_ip4_addr("0.0.0.0", 9001);
int r = uv_bind(&server, address);
if(r) {
uv_err_t err = uv_last_error();
fprintf(stderr, "bind: %s\n", uv_strerror(err));
return -1;
}
r = uv_listen(&server, 128, on_connection);
if(r) {
uv_err_t err = uv_last_error();
fprintf(stderr, "listen: %s\n", uv_strerror(err));
return -1;
}
uv_run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment