Advertisement
NickG

Untitled

Sep 9th, 2013
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <uv.h>
  4.  
  5. uv_loop_t *loop;
  6.  
  7. void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
  8.     *buf = uv_buf_init((char*) malloc(suggested_size), suggested_size);
  9. }
  10.  
  11. void echo_write(uv_write_t *req, int status) {
  12.     char *base = (char*) req->data;
  13.     free(base);
  14.     free(req);
  15. }
  16.  
  17. void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
  18.     if (nread < 0) {
  19.         uv_close((uv_handle_t*) client, NULL);
  20.         return;
  21.     }
  22.  
  23.     uv_write_t *req = (uv_write_t *) malloc(sizeof(uv_write_t));
  24.     req->data = (void*) buf->base;
  25.     uv_buf_t newbuf = uv_buf_init(buf->base, nread);
  26.     uv_write(req, client, &newbuf, 1, echo_write);
  27. }
  28.  
  29. void on_new_connection(uv_stream_t *server, int status) {
  30.     if (status < 0) {
  31.         return;
  32.     }
  33.  
  34.     uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
  35.     uv_tcp_init(loop, client);
  36.     if (uv_accept(server, (uv_stream_t*) client) < 0) {
  37.         uv_close((uv_handle_t*) client, NULL);
  38.     } else {
  39.         uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
  40.     }
  41. }
  42.  
  43. int main(int argc, char **argv) {
  44.     loop = uv_default_loop();
  45.     struct sockaddr_in bind_addr;
  46.     uv_tcp_t server;
  47.  
  48.     uv_tcp_init(loop, &server);
  49.     uv_ip4_addr("0.0.0.0", 7000, &bind_addr);
  50.     uv_tcp_bind(&server, (struct sockaddr*) &bind_addr);
  51.     uv_listen((uv_stream_t*) &server, 128, on_new_connection);
  52.     return uv_run(loop, UV_RUN_DEFAULT);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement