Advertisement
Guest User

Untitled

a guest
May 29th, 2016
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "uv.h"
  5.  
  6. static uv_loop_t *uv_loop;
  7. uv_udp_t handle;
  8.  
  9. static void on_alloc(uv_handle_t* client, size_t suggested_size, uv_buf_t* buf) {
  10.     buf->base = (char*) malloc(suggested_size);
  11.     buf->len = suggested_size;
  12. }
  13.  
  14. static void on_send(uv_udp_send_t *req, int status) {
  15.     if (status) {
  16.         fprintf(stderr, "Send error %s\n", uv_strerror(status));
  17.         return;
  18.     }
  19. }
  20.  
  21. static void on_recv(uv_udp_t* handle, ssize_t nread, const uv_buf_t* rcvbuf, const struct sockaddr* addr, unsigned flags) {
  22.     if (nread > 0) {
  23.         printf("Length:  %lu\n", nread);
  24.         printf("Message: %s", rcvbuf->base);
  25.        
  26.         uv_udp_send_t req;
  27.         uv_buf_t buf = uv_buf_init(rcvbuf->base, nread);
  28.        
  29.         uv_udp_send(&req, handle, &buf, 1, addr, on_send);
  30.     }
  31.  
  32.     free(rcvbuf->base);
  33. }
  34.  
  35. int main(int argc,char *argv[]) {
  36.     struct sockaddr_in addr;
  37.     uv_loop = uv_default_loop();
  38.    
  39.     uv_udp_init(uv_loop, &handle);
  40.     uv_ip4_addr("0.0.0.0", 3000, &addr);
  41.     uv_udp_bind(&handle, (const struct sockaddr*) &addr, 0);
  42.     uv_udp_recv_start(&handle, on_alloc, on_recv);
  43.    
  44.     uv_run(uv_loop, UV_RUN_DEFAULT);
  45.    
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement