Uv_send (sender side):
1#include"uv.h"2#include"task.h"3 4#include <stdio.h>5#include <stdlib.h>6#include <string.h>7 8 Staticuv_udp_t client;9 Ten Staticuv_loop_t *Loop; One A Static voidALLOC_CB (uv_handle_t*Handle, - size_t suggested_size, -uv_buf_t*buf) the { - Static Charslab[65536]; -Buf->Base=Slab; -Buf->len =sizeof(slab); + } - + Static voidCLOSE_CB (uv_handle_t*handle) A { at uv_is_closing (handle); - } - - Static voidCL_RECV_CB (uv_udp_t*Handle, - ssize_t Nread, - Constuv_buf_t*buf, in Const structsockaddr*addr, - unsigned flags) to { + if(Nread <0) - { the * } $ Panax Notoginseng if(Nread = =0) - { the return; + } A theprintf"I receive the message from server:%s\n", buf->Base); + -Uv_close ((uv_handle_t*) handle, CLOSE_CB); $ } $ - - Static voidCL_SEND_CB (uv_udp_send_t* req,intstatus) the { -Uv_udp_recv_start (req->handle, ALLOC_CB, CL_RECV_CB);Wuyi } the - intMainvoid) Wu { - structsockaddr_in addr; About uv_udp_send_t req; $ uv_buf_t buf; - intR; - -loop =Uv_default_loop (); A +R = uv_ip4_addr ("0.0.0.0",0, &addr); theR = Uv_udp_init (Loop, &client); -R = Uv_udp_bind (&client, (Const structsockaddr*) &addr,0); $R = Uv_udp_set_broadcast (&client,1); theUV_IP4_ADDR ("255.255.255.255",8899, &addr); theBUF = Uv_buf_init ("PING",4); theprintf"I am Sending message to server:%s.\n", buf.Base); theUv_udp_send (&req, -&Client, in&buf, the 1, the(Const structsockaddr*) &addr, About CL_SEND_CB); the the Uv_run (loop, uv_run_default); the + return 0; -}
Uv_recv (receiving side):
1#include"uv.h"2#include"task.h"3 4#include <stdio.h>5#include <stdlib.h>6#include <string.h>7 8 Staticuv_loop_t *Loop;9 Staticuv_udp_t server;Ten One Static voidALLOC_CB (uv_handle_t*Handle, A size_t suggested_size, -uv_buf_t*buf) - { the Static Charslab[65536]; - -Buf->Base=Slab; -Buf->len =sizeof(slab); + } - + Static voidCLOSE_CB (uv_handle_t*handle) A { at uv_is_closing (handle); - } - - Static voidSV_SEND_CB (uv_udp_send_t* req,intstatus) - { -Uv_close ((uv_handle_t*) req->handle, CLOSE_CB); in Free(req); - } to + Static voidSV_RECV_CB (uv_udp_t*Handle, - ssize_t Nread, the Constuv_buf_t*Rcvbuf, * Const structsockaddr*addr, $ unsigned flags)Panax Notoginseng { -uv_udp_send_t*req; the uv_buf_t sndbuf; + A if(Nread <0) the { + - } $ $ if(Nread = =0) - { - return; the } - Wuyiprintf"I receive the message from client:%s.\n", rcvbuf->Base); the - Uv_udp_recv_stop (handle); Wu -req =malloc(sizeof*req); About $Sndbuf = Uv_buf_init ("PONG",4); -Uv_udp_send (req, handle, &SNDBUF,1, addr, SV_SEND_CB); - } - A intMainvoid) + { the structsockaddr_in addr; - uv_udp_send_t req; $ uv_buf_t buf; the intR; the theloop =Uv_default_loop (); theR = uv_ip4_addr ("0.0.0.0",8899, &addr); -R = Uv_udp_init (Loop, &server); inR = Uv_udp_bind (&server, (Const structsockaddr*) &addr,0); theR = Uv_udp_recv_start (&server, ALLOC_CB, SV_RECV_CB); the About Uv_run (loop, uv_run_default); the the return 0; the}
Implementation of UDP receive/Send broadcast message code based on LIBUV library