EchoServer.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "PassiveSocket.h" // Include header for active socket object definition
  2. #define MAX_PACKET 4096
  3. int main(int argc, char **argv)
  4. {
  5. CPassiveSocket socket;
  6. CActiveSocket *pClient = NULL;
  7. //--------------------------------------------------------------------------
  8. // Initialize our socket object
  9. //--------------------------------------------------------------------------
  10. socket.Initialize();
  11. socket.Listen("localhost", 6667);
  12. while (true)
  13. {
  14. if ((pClient = socket.Accept()) != NULL)
  15. {
  16. int clientPort = socket.GetClientPort();
  17. printf("connected from %s:%d\n", socket.GetClientAddr(), clientPort);
  18. //----------------------------------------------------------------------
  19. // Receive request from the client.
  20. //----------------------------------------------------------------------
  21. while (1)
  22. {
  23. //printf("try receive\n");
  24. bool receivedData = false;
  25. int recBytes = 0;
  26. recBytes = pClient->Receive(MAX_PACKET);
  27. if (recBytes)
  28. {
  29. char *msg = (char *)pClient->GetData();
  30. msg[recBytes] = 0;
  31. printf("received message [%s]\n", msg);
  32. //------------------------------------------------------------------
  33. // Send response to client and close connection to the client.
  34. //------------------------------------------------------------------
  35. pClient->Send(pClient->GetData(), pClient->GetBytesReceived());
  36. receivedData = true;
  37. if (strncmp(msg, "stop", 4) == 0)
  38. {
  39. printf("Stop request received\n");
  40. break;
  41. }
  42. }
  43. if (!receivedData)
  44. {
  45. printf("Didn't receive data.\n");
  46. break;
  47. }
  48. }
  49. printf("Disconnecting client.\n");
  50. pClient->Close();
  51. delete pClient;
  52. }
  53. }
  54. //-----------------------------------------------------------------------------
  55. // Receive request from the client.
  56. //-----------------------------------------------------------------------------
  57. socket.Close();
  58. return 1;
  59. }