udp-connect-client.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. g++ udp-connect-client.cpp ../../objs/st/libst.a -g -O0 -o udp-connect-client &&
  3. ./udp-connect-client 127.0.0.1 8000 1
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <assert.h>
  8. #include "../../objs/st/st.h"
  9. #include <sys/socket.h>
  10. #include <arpa/inet.h>
  11. void* pfn(void* arg) {
  12. sockaddr_in addr = *(sockaddr_in*)arg;
  13. char* ip = inet_ntoa(addr.sin_addr);
  14. int port = ntohs(addr.sin_port);
  15. int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
  16. st_netfd_t stfd = st_netfd_open_socket(fd);
  17. printf("connect to %s:%d, fd=%d ok\n", ip, port, fd);
  18. while (true) {
  19. char data[] = "Hello world!";
  20. int r0 = st_sendto(stfd, data, sizeof(data), (sockaddr*)&addr, sizeof(sockaddr_in), ST_UTIME_NO_TIMEOUT);
  21. printf("fd #%d, send %dB %s, r0=%d\n", fd, (int)sizeof(data), data, r0);
  22. if (r0 != (int)sizeof(data)) {
  23. break;
  24. }
  25. st_usleep(800 * 1000);
  26. }
  27. st_netfd_close(stfd);
  28. return NULL;
  29. }
  30. int main(int argc, char** argv) {
  31. if (argc < 4) {
  32. printf("Usage: %s ip port workers\n", argv[0]);
  33. exit(-1);
  34. }
  35. st_init();
  36. const char* ip = argv[1];
  37. int port = ::atoi(argv[2]);
  38. int workers = ::atoi(argv[3]);
  39. printf("Start %d workers, to %s:%d\n", workers, ip, port);
  40. sockaddr_in addr;
  41. addr.sin_family = AF_INET;
  42. addr.sin_addr.s_addr = inet_addr(ip);
  43. addr.sin_port = htons(port);
  44. for (int i = 0; i < workers; i++) {
  45. st_thread_t thread = st_thread_create(pfn, &addr, 1, 0);
  46. assert(thread);
  47. }
  48. st_thread_exit(NULL);
  49. return 0;
  50. }