File: RecvAsync.cpp

package info (click to toggle)
bullet 3.06%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 15,012 kB
  • sloc: cpp: 243,705; lisp: 12,017; ansic: 11,175; python: 626; makefile: 133; sh: 75
file content (100 lines) | stat: -rw-r--r-- 1,990 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <pthread.h>
#include "PassiveSocket.h"

#ifdef WIN32
#include <windows.h>

// usually defined with #include <unistd.h>
static void sleep(unsigned int seconds)
{
	Sleep(seconds * 1000);
}
#endif

#define MAX_PACKET 4096
#define TEST_PACKET "Test Packet"

struct thread_data
{
	const char *pszServerAddr;
	short int nPort;
	int nNumBytesToReceive;
	int nTotalPayloadSize;
};

void *CreateTCPEchoServer(void *param)
{
	CPassiveSocket socket;
	CActiveSocket *pClient = NULL;
	struct thread_data *pData = (struct thread_data *)param;
	int nBytesReceived = 0;

	socket.Initialize();
	socket.Listen(pData->pszServerAddr, pData->nPort);

	if ((pClient = socket.Accept()) != NULL)
	{
		while (nBytesReceived != pData->nTotalPayloadSize)
		{
			if (nBytesReceived += pClient->Receive(pData->nNumBytesToReceive))
			{
				pClient->Send((const uint8 *)pClient->GetData(), pClient->GetBytesReceived());
			}
		}

		sleep(100);

		delete pClient;
	}

	socket.Close();

	return NULL;
}

int main(int argc, char **argv)
{
	pthread_t threadId;
	struct thread_data thData;
	CActiveSocket client;
	char result[1024];

	thData.pszServerAddr = "127.0.0.1";
	thData.nPort = 6789;
	thData.nNumBytesToReceive = 1;
	thData.nTotalPayloadSize = (int)strlen(TEST_PACKET);

	pthread_create(&threadId, 0, CreateTCPEchoServer, &thData);
	sleep(1);  // allow a second for the thread to create and listen

	client.Initialize();
	client.SetNonblocking();

	if (client.Open("127.0.0.1", 6789))
	{
		if (client.Send((uint8 *)TEST_PACKET, strlen(TEST_PACKET)))
		{
			int numBytes = -1;
			int bytesReceived = 0;

			client.Select();

			while (bytesReceived != strlen(TEST_PACKET))
			{
				numBytes = client.Receive(MAX_PACKET);

				if (numBytes > 0)
				{
					bytesReceived += numBytes;
					memset(result, 0, 1024);
					memcpy(result, client.GetData(), numBytes);
					printf("received %d bytes: '%s'\n", numBytes, result);
				}
				else
				{
					printf("Received %d bytes\n", numBytes);
				}
			}
		}
	}
}