Skip to content

Instantly share code, notes, and snippets.

@moccos
Last active August 29, 2015 14:08
Show Gist options
  • Save moccos/553824ba6f20aba7247a to your computer and use it in GitHub Desktop.
Save moccos/553824ba6f20aba7247a to your computer and use it in GitHub Desktop.
libuv test code.
#include <uv.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
static const int PORT = 12344;
void alloc_cb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
*buf = uv_buf_init((char*)malloc(suggested_size), suggested_size);
}
void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
printf("read_cb: read %d\n", (int)nread) ;
if (-1 == nread) {
printf("clise connection.\n");
uv_close((uv_handle_t*)stream, nullptr);
return;
}
char *p = buf->base;
for (auto i = 0; i < std::min((int)nread, 4); ++i) {
printf("%02x ", p[i]);
}
printf("\n");
free(buf->base);
}
void conn_cb(uv_stream_t* server, int status) {
printf("connection status: %d\n", status);
auto *p_client = (uv_tcp_t*)malloc(sizeof(uv_tcp_t));
uv_tcp_init(uv_default_loop(), p_client);
auto ret = uv_accept(server, (uv_stream_t*)p_client);
printf("accept: %d\n", ret);
if (0 == ret) {
uv_read_start((uv_stream_t*)p_client, alloc_cb, read_cb);
} else {
uv_close((uv_handle_t*)p_client, nullptr);
free(p_client);
}
}
int main(int argc, char **argv) {
// setup
uv_tcp_t tcp_t;
uv_tcp_init(uv_default_loop(), &tcp_t);
struct sockaddr_in local_addr;
uv_ip4_addr("0.0.0.0", PORT, &local_addr);
uv_tcp_bind(&tcp_t, (sockaddr*)&local_addr, 0);
// loop
uv_listen((uv_stream_t*)&tcp_t, 4, conn_cb);
printf("listening on: %d\n", PORT);
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
return 0;
}
% telnet localhost 12344
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
asdf
aaa
^]
telnet> q
Connection closed.
% ./uv_test
listening on: 12344
connection status: 0
accept: 0
read_cb: read 6
61 73 64 66
read_cb: read 5
61 61 61 0d
read_cb: read 2
0d 0a
read_cb: read -4095
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment