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