Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <uv.h>
- uv_loop_t *loop;
- void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
- *buf = uv_buf_init((char*) malloc(suggested_size), suggested_size);
- }
- void echo_write(uv_write_t *req, int status) {
- char *base = (char*) req->data;
- free(base);
- free(req);
- }
- void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
- if (nread < 0) {
- uv_close((uv_handle_t*) client, NULL);
- return;
- }
- uv_write_t *req = (uv_write_t *) malloc(sizeof(uv_write_t));
- req->data = (void*) buf->base;
- uv_buf_t newbuf = uv_buf_init(buf->base, nread);
- uv_write(req, client, &newbuf, 1, echo_write);
- }
- void on_new_connection(uv_stream_t *server, int status) {
- if (status < 0) {
- return;
- }
- uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
- uv_tcp_init(loop, client);
- if (uv_accept(server, (uv_stream_t*) client) < 0) {
- uv_close((uv_handle_t*) client, NULL);
- } else {
- uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
- }
- }
- int main(int argc, char **argv) {
- loop = uv_default_loop();
- struct sockaddr_in bind_addr;
- uv_tcp_t server;
- uv_tcp_init(loop, &server);
- uv_ip4_addr("0.0.0.0", 7000, &bind_addr);
- uv_tcp_bind(&server, (struct sockaddr*) &bind_addr);
- uv_listen((uv_stream_t*) &server, 128, on_new_connection);
- return uv_run(loop, UV_RUN_DEFAULT);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement