Skip to content

Instantly share code, notes, and snippets.

@joshthecoder
Last active December 18, 2015 20:59
Show Gist options
  • Save joshthecoder/5844580 to your computer and use it in GitHub Desktop.
Save joshthecoder/5844580 to your computer and use it in GitHub Desktop.
A TCP echo server written in Terra using libuv
uv = terralib.includecstring([[
#include <uv.h>
// Keep uv_write_s alive by tricking clang with a dummy function.
void __ignore(uv_write_t*);
]])
terralib.linklibrary("libuv.dylib")
stdlib = terralib.includec("stdlib.h")
stdio = terralib.includec("stdio.h")
terra alloc_buffer(handle : &uv.uv_handle_t, suggested_size : uv.size_t) : uv.uv_buf_t
return uv.uv_buf_init([&int8](stdlib.malloc(suggested_size)), suggested_size)
end
terra echo_write(req : &uv.uv_write_t, status : int)
stdlib.free(req.data)
stdlib.free(req)
end
terra echo_read(client : &uv.uv_stream_t, nread : uv.ssize_t, buf : uv.uv_buf_t)
if nread == -1 then
uv.uv_close([&uv.uv_handle_t](client), nil)
end
var req = [&uv.uv_write_t](stdlib.malloc(sizeof(uv.uv_write_t)))
req.data = buf.base
buf.len = nread
uv.uv_write(req, client, &buf, 1, echo_write)
end
terra on_connect(server : &uv.uv_stream_t, status : int)
if status == -1 then
return
end
var client = [&uv.uv_tcp_t](stdlib.malloc(sizeof(uv.uv_tcp_t)))
uv.uv_tcp_init(uv.uv_default_loop(), client)
if uv.uv_accept(server, [&uv.uv_stream_t](client)) == 0 then
uv.uv_read_start([&uv.uv_stream_t](client), alloc_buffer, echo_read)
else
uv.uv_close([&uv.uv_handle_t](client), nil)
end
end
terra main()
var loop = uv.uv_default_loop()
var server : uv.uv_tcp_t;
uv.uv_tcp_init(loop, &server)
var bind_addr : uv.sockaddr_in = uv.uv_ip4_addr("0.0.0.0", 2000)
uv.uv_tcp_bind(&server, bind_addr)
uv.uv_listen([&uv.uv_stream_t](&server), 128, on_connect)
uv.uv_run(loop, 0)
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment