Skip to content

Instantly share code, notes, and snippets.

@snatchev
Created March 27, 2013 16:55
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save snatchev/5255976 to your computer and use it in GitHub Desktop.
Save snatchev/5255976 to your computer and use it in GitHub Desktop.
a libuv evented tcp client
#include <stdio.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 uv_loop_t *loop;
static uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) {
return uv_buf_init(malloc(size), size);
}
void on_close(uv_handle_t* handle)
{
printf("closed.");
}
void on_write(uv_write_t* req, int status)
{
if (status) {
uv_err_t err = uv_last_error(loop);
fprintf(stderr, "uv_write error: %s\n", uv_strerror(err));
return;
}
printf("wrote.\n");
//uv_close((uv_handle_t*)req->handle, on_close);
}
void on_read(uv_stream_t* tcp, ssize_t nread, uv_buf_t buf)
{
if(nread >= 0) {
//printf("read: %s\n", tcp->data);
printf("read: %s\n", buf.base);
}
else {
//we got an EOF
uv_close((uv_handle_t*)tcp, on_close);
}
//cargo-culted
free(buf.base);
}
void on_connect(uv_connect_t* connection, int status)
{
printf("connected.\n");
uv_stream_t* stream = connection->handle;
uv_buf_t buffer[] = {
{.base = "hello", .len = 5},
{.base = "world", .len = 5}
};
uv_write_t request;
uv_write(&request, stream, buffer, 2, on_write);
uv_read_start(stream, alloc_cb, on_read);
}
int main(int argc, char **argv) {
loop = uv_default_loop();
uv_tcp_t socket;
uv_tcp_init(loop, &socket);
uv_tcp_keepalive(&socket, 1, 60);
struct sockaddr_in dest = uv_ip4_addr("0.0.0.0", 1234);
uv_connect_t connect;
uv_tcp_connect(&connect, &socket, dest, on_connect);
uv_run(loop, UV_RUN_DEFAULT);
}
@arijitvt
Copy link

Local request objects in dangling in the callback, since they are not available in the callback's context.

@kyze8439690
Copy link

kyze8439690 commented Jul 5, 2020

@arijitvt is right, should have malloc a uv_write_t and free it in on_write callback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment