File: EchoServer.cpp

package info (click to toggle)
bullet 2.87%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 14,272 kB
  • sloc: cpp: 204,241; ansic: 12,100; lisp: 12,017; python: 593; makefile: 136; sh: 8
file content (67 lines) | stat: -rw-r--r-- 2,046 bytes parent folder | download
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

#include "PassiveSocket.h"       // Include header for active socket object definition

#define MAX_PACKET 4096 

int main(int argc, char **argv)
{
    CPassiveSocket socket;
    CActiveSocket *pClient = NULL;

    //--------------------------------------------------------------------------
    // Initialize our socket object 
    //--------------------------------------------------------------------------
    socket.Initialize();

    socket.Listen("localhost", 6667);

    while (true)
    {
        if ((pClient = socket.Accept()) != NULL)
        {
			int clientPort = socket.GetClientPort();
			printf("connected from %s:%d\n", socket.GetClientAddr(),clientPort);
            //----------------------------------------------------------------------
            // Receive request from the client.
            //----------------------------------------------------------------------
            while (1)
			{
				//printf("try receive\n");
				bool receivedData = false;
				int recBytes = 0;
				recBytes = pClient->Receive(MAX_PACKET);
				if (recBytes)
				{
					char* msg = (char*) pClient->GetData();
					msg[recBytes]=0;
					printf("received message [%s]\n",msg);
					//------------------------------------------------------------------
					// Send response to client and close connection to the client.
					//------------------------------------------------------------------
					pClient->Send( pClient->GetData(), pClient->GetBytesReceived() );
					receivedData = true;
					if (strncmp(msg,"stop",4)==0)
					{
						printf("Stop request received\n");
						break;
					}
				}
				if (!receivedData)
				{
					printf("Didn't receive data.\n");
					break;
				} 
			}
			printf("Disconnecting client.\n");
			pClient->Close();
            delete pClient;
        }
    }

    //-----------------------------------------------------------------------------
    // Receive request from the client.
    //-----------------------------------------------------------------------------
    socket.Close();

    return 1;
}