2
0

st_utest_tcp.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* SPDX-License-Identifier: MIT */
  2. /* Copyright (c) 2013-2024 The SRS Authors */
  3. #include <st_utest.hpp>
  4. #include <st.h>
  5. #include <assert.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. #include <arpa/inet.h>
  9. #define ST_UTEST_PORT 26878
  10. #define ST_UTEST_TIMEOUT (100 * SRS_UTIME_MILLISECONDS)
  11. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  12. // The utest for ping-pong TCP server coroutine.
  13. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  14. void* tcp_server(void* /*arg*/)
  15. {
  16. int fd = -1;
  17. st_netfd_t stfd = NULL;
  18. StFdCleanup(fd, stfd);
  19. fd = socket(AF_INET, SOCK_STREAM, 0);
  20. ST_ASSERT_ERROR(fd == -1, fd, "Create socket");
  21. struct sockaddr_in addr;
  22. addr.sin_family = AF_INET;
  23. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  24. addr.sin_port = htons(ST_UTEST_PORT);
  25. int v = 1;
  26. int r0 = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(int));
  27. ST_ASSERT_ERROR(r0, r0, "Set SO_REUSEADDR");
  28. r0 = ::bind(fd, (const sockaddr*)&addr, sizeof(addr));
  29. ST_ASSERT_ERROR(r0, r0, "Bind socket");
  30. r0 = ::listen(fd, 10);
  31. ST_ASSERT_ERROR(r0, r0, "Listen socket");
  32. stfd = st_netfd_open_socket(fd);
  33. ST_ASSERT_ERROR(!stfd, fd, "Open ST socket");
  34. st_netfd_t client = NULL;
  35. StStfdCleanup(client);
  36. client = st_accept(stfd, NULL, NULL, ST_UTEST_TIMEOUT);
  37. ST_ASSERT_ERROR(!client, fd, "Accept client");
  38. return NULL;
  39. }
  40. void* tcp_client(void* /*arg*/)
  41. {
  42. int fd = -1;
  43. st_netfd_t stfd = NULL;
  44. StFdCleanup(fd, stfd);
  45. fd = socket(AF_INET, SOCK_STREAM, 0);
  46. ST_ASSERT_ERROR(fd == -1, fd, "Create socket");
  47. struct sockaddr_in addr;
  48. addr.sin_family = AF_INET;
  49. addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  50. addr.sin_port = htons(ST_UTEST_PORT);
  51. stfd = st_netfd_open_socket(fd);
  52. ST_ASSERT_ERROR(!stfd, fd, "Open ST socket");
  53. int r0 = st_connect(stfd, (const sockaddr*)&addr, sizeof(addr), ST_UTEST_TIMEOUT);
  54. ST_ASSERT_ERROR(r0, r0, "Connect to server");
  55. return NULL;
  56. }
  57. VOID TEST(TcpTest, TcpConnection)
  58. {
  59. st_thread_t svr = st_thread_create(tcp_server, NULL, 1, 0);
  60. EXPECT_TRUE(svr != NULL);
  61. st_thread_t client = st_thread_create(tcp_client, NULL, 1, 0);
  62. EXPECT_TRUE(client != NULL);
  63. ST_COROUTINE_JOIN(svr, r0);
  64. ST_COROUTINE_JOIN(client, r1);
  65. ST_EXPECT_SUCCESS(r0);
  66. ST_EXPECT_SUCCESS(r1);
  67. }