2
0

udp-server.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. g++ udp-server.cpp ../../objs/st/libst.a -g -O0 -o udp-server && ./udp-server 127.0.0.1 8000 3
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include "../../objs/st/st.h"
  8. #include <sys/socket.h>
  9. #include <arpa/inet.h>
  10. void* pfn(void* arg) {
  11. sockaddr_in addr = *(sockaddr_in*)arg;
  12. char* ip = inet_ntoa(addr.sin_addr);
  13. int port = ntohs(addr.sin_port);
  14. int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
  15. assert(fd > 0);
  16. if (true) {
  17. int v = 1;
  18. int r0 = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(int));
  19. assert(r0 != -1);
  20. }
  21. if (true) {
  22. int v = 1;
  23. int r0 = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(int));
  24. assert(r0 != -1);
  25. }
  26. if (true) {
  27. int r0 = bind(fd, (sockaddr*)&addr, sizeof(sockaddr_in));
  28. assert(!r0);
  29. }
  30. st_netfd_t stfd = st_netfd_open_socket(fd);
  31. printf("listen at %s:%d, fd=%d ok\n", ip, port, fd);
  32. while (true) {
  33. char buf[1600] = {0};
  34. sockaddr_in from;
  35. int nb_from = sizeof(from);
  36. int r0 = st_recvfrom(stfd, buf, sizeof(buf), (sockaddr*)&from, &nb_from, ST_UTIME_NO_TIMEOUT);
  37. printf("fd #%d, peer %s:%d, got %dB, %s\n", fd, inet_ntoa(from.sin_addr), ntohs(from.sin_port), r0, buf);
  38. if (r0 <= 0) {
  39. break;
  40. }
  41. st_usleep(10 * 1000);
  42. }
  43. st_netfd_close(stfd);
  44. return NULL;
  45. }
  46. int main(int argc, char** argv) {
  47. if (argc < 4) {
  48. printf("Usage: %s ip port workers\n", argv[0]);
  49. exit(-1);
  50. }
  51. st_init();
  52. const char* ip = argv[1];
  53. int port = ::atoi(argv[2]);
  54. int workers = ::atoi(argv[3]);
  55. printf("Start %d workers, at %s:%d\n", workers, ip, port);
  56. sockaddr_in addr;
  57. addr.sin_family = AF_INET;
  58. addr.sin_addr.s_addr = inet_addr(ip);
  59. addr.sin_port = htons(port);
  60. for (int i = 0; i < workers; i++) {
  61. st_thread_t thread = st_thread_create(pfn, &addr, 1, 0);
  62. assert(thread);
  63. }
  64. st_thread_exit(NULL);
  65. return 0;
  66. }