udp_echo_server.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * udp echo server
  3. *
  4. * @build make examples
  5. * @server bin/udp_echo_server 1234
  6. * @client bin/nc -u 127.0.0.1 1234
  7. * nc -u 127.0.0.1 1234
  8. *
  9. */
  10. #include "hloop.h"
  11. #include "hsocket.h"
  12. /*
  13. * @test kcp_server
  14. * #define TEST_KCP 1
  15. *
  16. * @build ./configure --with-kcp && make clean && make
  17. * @server bin/udp_echo_server 1234
  18. * @client bin/nc -k 127.0.0.1 1234
  19. *
  20. */
  21. #define TEST_KCP 0
  22. static void on_recvfrom(hio_t* io, void* buf, int readbytes) {
  23. printf("on_recvfrom fd=%d readbytes=%d\n", hio_fd(io), readbytes);
  24. char localaddrstr[SOCKADDR_STRLEN] = {0};
  25. char peeraddrstr[SOCKADDR_STRLEN] = {0};
  26. printf("[%s] <=> [%s]\n",
  27. SOCKADDR_STR(hio_localaddr(io), localaddrstr),
  28. SOCKADDR_STR(hio_peeraddr(io), peeraddrstr));
  29. char* str = (char*)buf;
  30. printf("< %.*s", readbytes, str);
  31. // echo
  32. printf("> %.*s", readbytes, str);
  33. hio_write(io, buf, readbytes);
  34. #if TEST_KCP
  35. if (strncmp(str, "CLOSE", 5) == 0) {
  36. hio_close_rudp(io, hio_peeraddr(io));
  37. }
  38. #endif
  39. }
  40. int main(int argc, char** argv) {
  41. if (argc < 2) {
  42. printf("Usage: %s port|path\n", argv[0]);
  43. return -10;
  44. }
  45. const char* host = "0.0.0.0";
  46. int port = atoi(argv[1]);
  47. #if ENABLE_UDS
  48. if (port == 0) {
  49. host = argv[1];
  50. port = -1;
  51. }
  52. #endif
  53. hloop_t* loop = hloop_new(0);
  54. hio_t* io = hloop_create_udp_server(loop, host, port);
  55. if (io == NULL) {
  56. return -20;
  57. }
  58. #if TEST_KCP
  59. hio_set_kcp(io, NULL);
  60. #endif
  61. hio_setcb_read(io, on_recvfrom);
  62. hio_read(io);
  63. hloop_run(loop);
  64. hloop_free(&loop);
  65. return 0;
  66. }