RecvAsync.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <pthread.h>
  2. #include "PassiveSocket.h"
  3. #ifdef WIN32
  4. #include <windows.h>
  5. // usually defined with #include <unistd.h>
  6. static void sleep(unsigned int seconds)
  7. {
  8. Sleep(seconds * 1000);
  9. }
  10. #endif
  11. #define MAX_PACKET 4096
  12. #define TEST_PACKET "Test Packet"
  13. struct thread_data
  14. {
  15. const char *pszServerAddr;
  16. short int nPort;
  17. int nNumBytesToReceive;
  18. int nTotalPayloadSize;
  19. };
  20. void *CreateTCPEchoServer(void *param)
  21. {
  22. CPassiveSocket socket;
  23. CActiveSocket *pClient = NULL;
  24. struct thread_data *pData = (struct thread_data *)param;
  25. int nBytesReceived = 0;
  26. socket.Initialize();
  27. socket.Listen(pData->pszServerAddr, pData->nPort);
  28. if ((pClient = socket.Accept()) != NULL)
  29. {
  30. while (nBytesReceived != pData->nTotalPayloadSize)
  31. {
  32. if (nBytesReceived += pClient->Receive(pData->nNumBytesToReceive))
  33. {
  34. pClient->Send((const uint8 *)pClient->GetData(), pClient->GetBytesReceived());
  35. }
  36. }
  37. sleep(100);
  38. delete pClient;
  39. }
  40. socket.Close();
  41. return NULL;
  42. }
  43. int main(int argc, char **argv)
  44. {
  45. pthread_t threadId;
  46. struct thread_data thData;
  47. CActiveSocket client;
  48. char result[1024];
  49. thData.pszServerAddr = "127.0.0.1";
  50. thData.nPort = 6789;
  51. thData.nNumBytesToReceive = 1;
  52. thData.nTotalPayloadSize = (int)strlen(TEST_PACKET);
  53. pthread_create(&threadId, 0, CreateTCPEchoServer, &thData);
  54. sleep(1); // allow a second for the thread to create and listen
  55. client.Initialize();
  56. client.SetNonblocking();
  57. if (client.Open("127.0.0.1", 6789))
  58. {
  59. if (client.Send((uint8 *)TEST_PACKET, strlen(TEST_PACKET)))
  60. {
  61. int numBytes = -1;
  62. int bytesReceived = 0;
  63. client.Select();
  64. while (bytesReceived != strlen(TEST_PACKET))
  65. {
  66. numBytes = client.Receive(MAX_PACKET);
  67. if (numBytes > 0)
  68. {
  69. bytesReceived += numBytes;
  70. memset(result, 0, 1024);
  71. memcpy(result, client.GetData(), numBytes);
  72. printf("received %d bytes: '%s'\n", numBytes, result);
  73. }
  74. else
  75. {
  76. printf("Received %d bytes\n", numBytes);
  77. }
  78. }
  79. }
  80. }
  81. }