Skip to content

Instantly share code, notes, and snippets.

@igorzi igorzi/gist:1227502
Created Sep 19, 2011

Embed
What would you like to do?
#include <uv.h>
#include <io.h>
#include <stdio.h>
#include <string.h>
char message[] = "HTTP 1.1 200 OK\r\nContent-Length: 12\r\nConnection: close\r\n\r\nhello world\n";
#define CHECK(r) \
if (!(r)) abort();
#define LOG(msg, ...) \
printf("Server %d: " ## msg, GetCurrentThreadId(), __VA_ARGS__); \
void cl_close_cb(uv_handle_t* handle) {
free(handle);
}
void cl_write_cb(uv_write_t* req, int status) {
CHECK(status == 0);
uv_close((uv_handle_t*) req->handle, cl_close_cb);
free(req);
}
void cl_write(uv_tcp_t* handle) {
int r;
uv_buf_t buf = uv_buf_init(message, (sizeof message) - 1);
uv_write_t* req = (uv_write_t*)malloc(sizeof *req);
r = uv_write(req, (uv_stream_t*) handle, &buf, 1, cl_write_cb);
if (r) {
LOG("error");
uv_close((uv_handle_t*) handle, cl_close_cb);
free(req);
}
}
void connection_cb(uv_stream_t* server, int status) {
int r;
uv_tcp_t* client = (uv_tcp_t*) malloc(sizeof *client);
CHECK(status == 0);
r = uv_tcp_init(server->loop, client);
CHECK(r == 0);
r = uv_accept(server, (uv_stream_t*) client);
CHECK(r == 0);
cl_write(client);
}
int main(int argv, char** argc) {
int r;
uv_tcp_t server;
r = uv_tcp_init(uv_default_loop(), &server);
CHECK(r == 0);
r = uv_tcp_bind(&server, uv_ip4_addr("0.0.0.0", 80));
CHECK(r == 0);
// Start listening now
LOG("listen\n");
r = uv_listen((uv_stream_t*) &server, 200, connection_cb);
CHECK(r == 0);
uv_run(uv_default_loop());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.