2
0

udp-client.cpp 1.5 KB

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