Advertisement
Guest User

kodutoo1final

a guest
Oct 19th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 27.46 KB | None | 0 0
  1. #include "stdafx.h"
  2. #define _WINSOCK_DEPRECATED_NO_WARNINGS
  3. #include "Winsock2.h" // necessary for sockets, Windows.h is not needed.
  4. #include "mswsock.h"
  5. #include "process.h"  // necessary for threading
  6. #include "tchar.h"
  7. #include "time.h"
  8.  
  9. //
  10. // Global variables
  11. //
  12. TCHAR CommandBuf[81];
  13. HANDLE hCommandGot;       // event "the user has typed a command"
  14. HANDLE hStopCommandGot;   // event "the main thread has recognized that it was the stop command"
  15. HANDLE hCommandProcessed; // event "the main thread has finished the processing of command"
  16. HANDLE hConnectCommandGot;
  17. HANDLE hCloseNetCommandGot;
  18. HANDLE hFile;
  19.  
  20. HANDLE hReadKeyboard;     // keyboard reading thread handle
  21. HANDLE hStdIn;            // stdin standard input stream handle
  22. WSADATA WsaData;          // filled during Winsock initialization
  23. DWORD Error;
  24. DWORD nWritten;
  25. SOCKET hClientSocket = INVALID_SOCKET;
  26. sockaddr_in ClientSocketInfo;
  27. HANDLE hReceiveNet;       // TCP/IP info reading thread handle
  28. HANDLE hSendNet;
  29. BOOL SocketError;
  30. BOOL SendPassword = FALSE;
  31. BOOL SendStart = FALSE;
  32. BOOL SendStop = FALSE;
  33. BOOL ConnectionStatus = FALSE; //describes general status of connection
  34. BOOL SecureConnectionEstablished = FALSE;
  35. BOOL ActiveDataStream = FALSE;
  36.  
  37. #pragma warning (disable : 4290)
  38. #pragma warning (disable : 4996)
  39.  
  40. //
  41. // Prototypes
  42. //
  43. unsigned int __stdcall ReadKeyboard(void* pArguments);
  44. unsigned int __stdcall ReceiveNet(void* pArguments);
  45. unsigned int __stdcall SendNet(void* pArguments);
  46. BOOL CreateConnection(void);
  47. void ProcessPacket(WSABUF *Databuf);
  48.  
  49.  
  50. //****************************************************************************************************************
  51. //                                 MAIN THREAD
  52. //****************************************************************************************************************
  53. int _tmain(int argc, char *argv[])
  54. {
  55.  
  56.     //char *logfilename = argv[1];
  57.     //
  58.     // opening file, was made, using file  example from examples
  59.     //
  60.     /*
  61.     if (argv == NULL)
  62.     {
  63.         printf("WTF NULL!!??\n");
  64.     }
  65.     */
  66.     if (argc == 2) //kui sisestati eraldi failinimi, kuhu kirjutada
  67.     {
  68.         _tprintf("%s\n", argv[1]);
  69.         hFile = CreateFile((argv[1]), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  70.     }
  71.     else //muidu läheb kasutusse default failinimi
  72.         hFile = CreateFile(("Logfile.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  73.         //logfilename = "Logfile.txt";
  74.         //strcpy(logfilename, "Logfile.txt");
  75.  
  76.  
  77.    
  78.     if (hFile == INVALID_HANDLE_VALUE)
  79.     {
  80.         _tprintf(_T("Unable to create file, error %d\n"), GetLastError());
  81.         return 1;
  82.     }
  83.  
  84.     //
  85.     // Initializations for multithreading
  86.     //
  87.  
  88.     if (!(hCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
  89.         !(hStopCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
  90.         !(hCommandProcessed = CreateEvent(NULL, TRUE, TRUE, NULL)) ||
  91.         !(hConnectCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
  92.         !(hCloseNetCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)))
  93.     {
  94.         _tprintf(_T("CreateEvent() failed, error %d\n"), GetLastError());
  95.         return 1;
  96.     }
  97.     //
  98.     // Prepare keyboard, start the thread
  99.     //
  100.     hStdIn = GetStdHandle(STD_INPUT_HANDLE);
  101.     if (hStdIn == INVALID_HANDLE_VALUE)
  102.     {
  103.         _tprintf(_T("GetStdHandle() failed, error %d\n"), GetLastError());
  104.         return 1;
  105.     }
  106.     if (!SetConsoleMode(hStdIn, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT))
  107.     {
  108.         _tprintf(_T("SetConsoleMode() failed, error %d\n"), GetLastError());
  109.         return 1;
  110.     }
  111.     if (!(hReadKeyboard = (HANDLE)_beginthreadex(NULL, 0, &ReadKeyboard, NULL, 0, NULL)))
  112.     {
  113.         _tprintf(_T("Unable to create keyboard thread\n"));
  114.         return 1;
  115.     }
  116.     //ConnectionStatus = CreateConnection(); //alamfunktsioon, tekitab yhenduse
  117.    
  118.     /*
  119.     //
  120.     // Initializations for socket
  121.     //
  122.     if (Error = WSAStartup(MAKEWORD(2, 0), &WsaData)) // Initialize Windows socket support
  123.     {
  124.     _tprintf(_T("WSAStartup() failed, error %d\n"), Error);
  125.     SocketError = TRUE;
  126.     }
  127.     else if ((hClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
  128.     {
  129.     _tprintf(_T("socket() failed, error %d\n"), WSAGetLastError());
  130.     SocketError = TRUE;
  131.     }
  132.     //
  133.     // Connect client to server
  134.     //
  135.     if (!SocketError)
  136.     {
  137.     ClientSocketInfo.sin_family = AF_INET;
  138.     ClientSocketInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
  139.     ClientSocketInfo.sin_port = htons(1234);  // port number is selected just for example
  140.     if (connect(hClientSocket, (SOCKADDR*)&ClientSocketInfo, sizeof(ClientSocketInfo)) == SOCKET_ERROR)
  141.     {
  142.     _tprintf(_T("Unable to connect to server, error %d\n"), WSAGetLastError());
  143.     SocketError = TRUE;
  144.     }
  145.     }
  146.     //
  147.     // Start net receiving thread
  148.     //
  149.     if (!SocketError)
  150.     {
  151.     if (!(hReceiveNet = (HANDLE)_beginthreadex(NULL, 0, &ReceiveNet, NULL, 0, NULL)))
  152.     {
  153.     _tprintf(_T("Unable to create socket receiving thread\n"));
  154.     goto out;
  155.     }
  156.     //
  157.     // Start net sending thread
  158.     //
  159.  
  160.     if (!(hSendNet = (HANDLE)_beginthreadex(NULL, 0, &SendNet, NULL, 0, NULL)))
  161.     {
  162.     _tprintf(_T("Unable to create socket sending thread\n"));
  163.     goto out;
  164.     }
  165.  
  166.     }
  167.     */
  168.     //
  169.     // Main processing loop
  170.     //
  171.     while (TRUE)
  172.     {
  173.         if (WaitForSingleObject(hCommandGot, INFINITE) != WAIT_OBJECT_0)
  174.         { // Wait until the command has arrived (i.e. until CommandGot is signaled)
  175.             _tprintf(_T("WaitForSingleObject() failed, error %d\n"), GetLastError());
  176.             goto out;
  177.         }
  178.         ResetEvent(hCommandGot); // CommandGot back to unsignaled
  179.         if (!_tcsicmp(CommandBuf, _T("exit"))) // Case-insensitive comparation
  180.         {
  181.             SetEvent(hStopCommandGot); // To force the other threads to quit
  182.             break;
  183.         }
  184.         else if (!_tcsicmp(CommandBuf, _T("connect"))) // tuleb connectimis command
  185.         {
  186.             _tprintf("Command connect accepted\n");
  187.  
  188.             if (SecureConnectionEstablished == FALSE)
  189.             {
  190.                 if (ConnectionStatus == FALSE || SendPassword == FALSE)
  191.                 {
  192.                     ConnectionStatus = CreateConnection();
  193.                     if (ConnectionStatus == FALSE) //ehk ühendust ei õnnestunud luua, sulgeme threadid ka
  194.                     {
  195.                         SetEvent(hCloseNetCommandGot);
  196.  
  197.                         if (hReceiveNet)
  198.                         {
  199.                             WaitForSingleObject(hReceiveNet, INFINITE); // Wait until the end of receive thread
  200.                             CloseHandle(hReceiveNet);
  201.                         }
  202.                         if (hSendNet)
  203.                         {
  204.                             WaitForSingleObject(hSendNet, INFINITE); // Wait until the end of receive thread
  205.                             CloseHandle(hSendNet);
  206.                         }
  207.                         ResetEvent(hCloseNetCommandGot);
  208.                         if (hClientSocket != INVALID_SOCKET)
  209.                         {
  210.                             if (shutdown(hClientSocket, SD_RECEIVE) == SOCKET_ERROR)
  211.                             {
  212.                                 if ((Error = WSAGetLastError()) != WSAENOTCONN) // WSAENOTCONN means that the connection was not established,
  213.                                                                                 // so the shut down was senseless
  214.                                     _tprintf(_T("shutdown() failed, error %d\n"), WSAGetLastError());
  215.                             }
  216.                             closesocket(hClientSocket);
  217.                         }
  218.                         WSACleanup(); // clean Windows sockets support
  219.                         SocketError = FALSE;
  220.                     }
  221.                 }
  222.                 else
  223.                 {
  224.                     _tprintf("Establishing secure connection\n");
  225.                     SetEvent(hConnectCommandGot); //event, et connect käsk anti käiku
  226.                 }
  227.             }
  228.             else
  229.             {
  230.                 _tprintf("Secure connection has already been made\n");
  231.             }
  232.             SetEvent(hCommandProcessed); //event, et käsu täitmine on lõppenud
  233.         }
  234.         else if (!_tcsicmp(CommandBuf, _T("start"))) // tuleb connectimis command
  235.         {
  236.             _tprintf("Command start accepted\n");
  237.             if (ConnectionStatus == TRUE)
  238.             {
  239.                 if (ActiveDataStream == FALSE)
  240.                 {
  241.                     SetEvent(hConnectCommandGot); //event, et connect käsk anti käiku
  242.                     SendStart = TRUE;
  243.                     SetEvent(hCommandProcessed); //event, et käsu täitmine on lõppenud
  244.                 }
  245.             }
  246.             else
  247.                 _tprintf("Connection not established yet, try connect instead\n");
  248.  
  249.             SetEvent(hCommandProcessed);
  250.         }
  251.         else if (!_tcsicmp(CommandBuf, _T("break"))) // tuleb connectimis command
  252.         {
  253.             _tprintf("Command break accepted\n");
  254.  
  255.             if (ActiveDataStream == TRUE)
  256.             {
  257.                 ActiveDataStream = FALSE;
  258.                 SendStart = FALSE;
  259.                 //event, et käsu täitmine on lõppenud
  260.             }
  261.             else
  262.                 _tprintf("Active connection is already down\n");
  263.             SetEvent(hCommandProcessed);
  264.         }
  265.         else if (!_tcsicmp(CommandBuf, _T("stop"))) // Case-insensitive comparation
  266.         {
  267.             //_tprintf("Command Stop Accepted, nothing to do yet\n");
  268.             //SetEvent(hCloseNetCommandGot);
  269.             if (ConnectionStatus == TRUE || SecureConnectionEstablished == TRUE)
  270.             {
  271.                 _tprintf("Closing connection\n");
  272.                 SendStop = TRUE;
  273.                 SetEvent(hConnectCommandGot);
  274.                
  275.                 /*
  276.                 while (SendStop == TRUE)
  277.                 {
  278.                     _tprintf("waiting for sending thread to send stop message\n");
  279.                 }
  280.                 */
  281.                 SetEvent(hCloseNetCommandGot);
  282.  
  283.                 if (hReceiveNet)
  284.                 {
  285.                     WaitForSingleObject(hReceiveNet, INFINITE); // Wait until the end of receive thread
  286.                     CloseHandle(hReceiveNet);
  287.                 }
  288.                 if (hSendNet)
  289.                 {
  290.                     WaitForSingleObject(hSendNet, INFINITE); // Wait until the end of receive thread
  291.                     CloseHandle(hSendNet);
  292.                 }
  293.                 //_tprintf("Closing connection 2\n");
  294.                 /*
  295.                 if (hClientSocket != INVALID_SOCKET)
  296.                 {
  297.                     if (shutdown(hClientSocket, SD_RECEIVE) == SOCKET_ERROR)
  298.                     {
  299.                         if ((Error = WSAGetLastError()) != WSAENOTCONN) // WSAENOTCONN means that the connection was not established,
  300.                                                                         // so the shut down was senseless
  301.                             _tprintf(_T("shutdown() failed, error %d\n"), WSAGetLastError());
  302.                     }
  303.                     closesocket(hClientSocket);
  304.  
  305.                 }
  306.                 */
  307.                 //WSACleanup(); //Vajalik windows socketis oleva kama puhastamiseks
  308.                
  309.                 ConnectionStatus = FALSE;
  310.                 SecureConnectionEstablished = FALSE;
  311.                 ActiveDataStream = FALSE;
  312.                 ResetEvent(hCloseNetCommandGot);
  313.             }
  314.             else
  315.                 _tprintf("Connection is already down\n");
  316.  
  317.             SetEvent(hCommandProcessed);
  318.         }
  319.         else
  320.         {
  321.             _tprintf(_T("Command \"%s\" not recognized\n"), CommandBuf);
  322.             SetEvent(hCommandProcessed); // To allow the keyboard reading thread to continue
  323.         }
  324.     }
  325.     //
  326.     // Shut down
  327.     //
  328. out:
  329.     if (hReadKeyboard)
  330.     {
  331.         WaitForSingleObject(hReadKeyboard, INFINITE); // Wait until the end of keyboard thread
  332.         CloseHandle(hReadKeyboard);
  333.     }
  334.     if (hReceiveNet)
  335.     {
  336.         WaitForSingleObject(hReceiveNet, INFINITE); // Wait until the end of receive thread
  337.         CloseHandle(hReceiveNet);
  338.     }
  339.     if (hSendNet)
  340.     {
  341.         WaitForSingleObject(hSendNet, INFINITE); // Wait until the end of receive thread
  342.         CloseHandle(hSendNet);
  343.     }
  344.     if (hClientSocket != INVALID_SOCKET)
  345.     {
  346.         if (shutdown(hClientSocket, SD_RECEIVE) == SOCKET_ERROR)
  347.         {
  348.             if ((Error = WSAGetLastError()) != WSAENOTCONN) // WSAENOTCONN means that the connection was not established,
  349.                                                             // so the shut down was senseless
  350.                 _tprintf(_T("shutdown() failed, error %d\n"), WSAGetLastError());
  351.         }
  352.         closesocket(hClientSocket);
  353.     }
  354.     WSACleanup(); // clean Windows sockets support
  355.     CloseHandle(hStopCommandGot);
  356.     CloseHandle(hCommandGot);
  357.     CloseHandle(hCommandProcessed);
  358.     CloseHandle(hConnectCommandGot);
  359.     CloseHandle(hCloseNetCommandGot);
  360.  
  361.     CloseHandle(hFile); //closing file at the end of program cycle
  362.     return 0;
  363. }
  364. //**************************************************************************************************************
  365. //                          KEYBOARD READING THREAD
  366. //**************************************************************************************************************
  367. unsigned int __stdcall ReadKeyboard(void* pArguments)
  368. {
  369.     DWORD nReadChars;
  370.     HANDLE KeyboardEvents[2];
  371.     KeyboardEvents[1] = hCommandProcessed;
  372.     KeyboardEvents[0] = hStopCommandGot;
  373.     DWORD WaitResult;
  374.     //
  375.     // Reading loop
  376.     //
  377.     while (TRUE)
  378.     {
  379.         WaitResult = WaitForMultipleObjects(2, KeyboardEvents,
  380.             FALSE, // wait until one of the events becomes signaled
  381.             INFINITE);
  382.         // Waiting until hCommandProcessed or hStopCommandGot becomes signaled. Initially hCommandProcessed
  383.         // is signaled, so at the beginning WaitForMultipleObjects() returns immediately with WaitResult equal
  384.         // with WAIT_OBJECT_0 + 1.
  385.         if (WaitResult == WAIT_OBJECT_0)
  386.             return 0;  // Stop command, i.e. hStopCommandGot is signaled
  387.         else if (WaitResult == WAIT_OBJECT_0 + 1)
  388.         { // If the signaled event is hCommandProcessed, the WaitResult is WAIT_OBJECT_0 + 1
  389.             _tprintf(_T("Insert command\n"));
  390.             if (!ReadConsole(hStdIn, CommandBuf, 80, &nReadChars, NULL))
  391.             { // The problem is that when we already are in this function, the only way to leave it
  392.               // is to type something and then press ENTER. So we cannot step into this function at any moment.
  393.               // WaitForMultipleObjects() prevents it.
  394.                 _tprintf(_T("ReadConsole() failed, error %d\n"), GetLastError());
  395.                 return 1;
  396.             }
  397.             CommandBuf[nReadChars - 2] = 0; // The command in buf ends with "\r\n", we have to get rid of them
  398.             ResetEvent(hCommandProcessed);
  399.             // Set hCommandProcessed to non-signaled. Therefore WaitForMultipleObjects() blocks the keyboard thread.
  400.             // When the main thread has ended the analyzing of command, it sets hCommandprocessed or hStopCommandGot
  401.             // to signaled and the keyboard thread can continue.
  402.             SetEvent(hCommandGot);
  403.             // Set hCommandGot event to signaled. Due to that WaitForSingleObject() in the main thread
  404.             // returns, the waiting stops and the analyzing of inserted command may begin
  405.         }
  406.         else
  407.         {   // waiting failed
  408.             _tprintf(_T("WaitForMultipleObjects()failed, error %d\n"), GetLastError());
  409.             return 1;
  410.         }
  411.     }
  412.     return 0;
  413. }
  414. //********************************************************************************************************************
  415. //                          TCP/IP INFO RECEIVING THREAD
  416. //********************************************************************************************************************
  417. unsigned int __stdcall ReceiveNet(void* pArguments)
  418. {
  419.     //
  420.     // Preparations
  421.     //
  422.     WSABUF DataBuf;  // Buffer for received data is a structure
  423.     char ArrayInBuf[2048];
  424.     DataBuf.buf = &ArrayInBuf[0];
  425.     DataBuf.len = 2048;
  426.     DWORD nReceivedBytes = 0, ReceiveFlags = 0;
  427.     HANDLE NetEvents[3];
  428.     NetEvents[2] = hCloseNetCommandGot;
  429.     NetEvents[0] = hStopCommandGot;
  430.     WSAOVERLAPPED Overlapped;
  431.     memset(&Overlapped, 0, sizeof Overlapped);
  432.     Overlapped.hEvent = NetEvents[1] = WSACreateEvent(); // manual and nonsignaled
  433.     DWORD Result, Error;
  434.     wchar_t *DataPointer;
  435.     wchar_t *identifier = L"Identify";
  436.     wchar_t *accepter = L"Accepted";
  437.  
  438.  
  439.     //
  440.     // Receiving loop
  441.     //
  442.     while (TRUE)
  443.     {
  444.         Result = WSARecv(hClientSocket,
  445.             &DataBuf,
  446.             1,  // no comments here
  447.             &nReceivedBytes,
  448.             &ReceiveFlags, // no comments here
  449.             &Overlapped,
  450.             NULL);  // no comments here
  451.         if (Result == SOCKET_ERROR)
  452.         {  // Returned with socket error, let us examine why
  453.             if ((Error = WSAGetLastError()) != WSA_IO_PENDING)
  454.             {  // Unable to continue, for example because the server has closed the connection
  455.                 _tprintf(_T("WSARecv() failed, error %d\n"), Error);
  456.                 goto out;
  457.             }
  458.             DWORD WaitResult = WSAWaitForMultipleEvents(3, NetEvents, FALSE, WSA_INFINITE, FALSE); // wait for data
  459.             switch (WaitResult) // analyse why the waiting ended
  460.             {
  461.             case WAIT_OBJECT_0:                 // Waiting stopped because hStopCommandGot has become signaled, i.e. the user has decided to exit
  462.  
  463.                 goto out;
  464.                 break;
  465.             case WAIT_OBJECT_0 + 1:
  466.                 // Waiting stopped because Overlapped.hEvent is now signaled, i.e. the receiving operation has ended.
  467.                 // Now we have to see how many bytes we have got.
  468.                 WSAResetEvent(NetEvents[1]); // to be ready for the next data package
  469.                 if (WSAGetOverlappedResult(hClientSocket, &Overlapped, &nReceivedBytes, FALSE, &ReceiveFlags))
  470.                 {
  471.  
  472.  
  473.                     _tprintf(_T("%d bytes received\n"), nReceivedBytes);
  474.                     // Here should follow the processing of received data
  475.  
  476.                     DataPointer = (wchar_t*)(DataBuf.buf + 4);
  477.                     //_tprintf(_T("%ls\n"), DataPointer);
  478.  
  479.  
  480.                     if (!wcscmp(DataPointer, identifier)) //detectime, kas sisendiks tuli Identify
  481.                     {
  482.                         _tprintf("Identity detected, use connect command again\n");
  483.                         //siia peaks tulema event, et saatja saadaks parooli
  484.                         //SetEvent(hSendCommandGot);
  485.                         SendPassword = TRUE;
  486.                         SetEvent(hConnectCommandGot);
  487.                     }
  488.                     else if (!wcscmp(DataPointer, accepter))
  489.                     {
  490.                         _tprintf("Secure connection Established\n");
  491.                     }
  492.                     else
  493.                     {
  494.                         _tprintf("Got packet!\n");
  495.                         ProcessPacket(&DataBuf);
  496.                     }
  497.  
  498.                     if (ActiveDataStream == TRUE)
  499.                     {
  500.                         //siia tuleb sissetulnud data processimine
  501.                         SetEvent(hConnectCommandGot); //palume uue paketi saata
  502.                         SendStart = TRUE;
  503.                     }
  504.                     break;
  505.                 }
  506.                 else
  507.                 {   // Fatal problems
  508.                     _tprintf(_T("WSAGetOverlappedResult() failed, error %d\n"), GetLastError());
  509.                     goto out;
  510.                     break;
  511.                 }
  512.                 /*
  513.                 case WAIT_OBJECT_0 + 2: //tuli command neti sulgemiseks
  514.  
  515.                 goto out;
  516.                 */
  517.             case WAIT_OBJECT_0 + 2:
  518.             {
  519.                 _tprintf("Closing receiving net thread\n");
  520.                 goto out;
  521.                 break;
  522.             }
  523.  
  524.             default: // Fatal problems
  525.                 _tprintf(_T("WSAWaitForMultipleEvents() failed in receiving thread, error %d\n"), WSAGetLastError());
  526.                 goto out;
  527.             }
  528.         }
  529.         else
  530.         {  // Returned immediately without socket error
  531.             if (!nReceivedBytes)
  532.             {  // When the receiving function has read nothing and returned immediately, the connection is off  
  533.                 _tprintf(_T("Server has closed the connection\n"));
  534.                 goto out;
  535.             }
  536.             else
  537.             {
  538.  
  539.                 _tprintf(_T("%d bytes received\n"), nReceivedBytes);
  540.                 // Here should follow the processing of received data
  541.  
  542.             }
  543.         }
  544.     }
  545. out:
  546.     WSACloseEvent(NetEvents[1]);
  547.     return 0;
  548. }
  549.  
  550.  
  551.  
  552. //********************************************************************************************************************
  553. //                          TCP/IP INFO SENDING THREAD
  554. //********************************************************************************************************************
  555. /*
  556. thread will use WSASend function to send data
  557. */
  558.  
  559.  
  560. unsigned int __stdcall SendNet(void* pArguments)
  561. {
  562.     WSABUF DataBuf;
  563.     DWORD Result, Error, nSendBytes = 0, SendFlags = 0;
  564.  
  565.     char ArrayOutBuf[1024];
  566.     DataBuf.buf = &ArrayOutBuf[0];
  567.     DataBuf.len = strlen(ArrayOutBuf);
  568.  
  569.     wchar_t *Wordtosend;
  570.  
  571.     wchar_t *PointertoWriteWord = (wchar_t*)DataBuf.buf + 2;
  572.     DWORD SendWordLength;
  573.  
  574.     HANDLE OutputEvents[4];
  575.     OutputEvents[0] = hStopCommandGot; //sending operation cancelling
  576.     OutputEvents[2] = hConnectCommandGot;
  577.     OutputEvents[3] = hCloseNetCommandGot;
  578.     WSAOVERLAPPED SendOverlapped;
  579.     //_tprintf("Oleme saatmise thread'i joudnud\n");
  580.  
  581.     SendOverlapped.hEvent = OutputEvents[1] = WSACreateEvent(); // manual and nonsignaled
  582.  
  583.     while (TRUE)
  584.     {
  585.  
  586.         //_tprintf("ootame saatmise k2sku...\n");
  587.         DWORD WaitResult = WaitForMultipleObjects(4, OutputEvents, FALSE, INFINITE);
  588.         switch (WaitResult) //vastavalt sellele, mis hetkel waitresult on, on tegevus
  589.         {
  590.         case WAIT_OBJECT_0: //siin lahkume threadist e. tulnud on event Stop
  591.         {
  592.             goto out;
  593.             break;
  594.         }
  595.         case WAIT_OBJECT_0 + 1:
  596.         {
  597.             WSAResetEvent(OutputEvents[1]);
  598.             //goto out;
  599.            
  600.         }
  601.  
  602.         case WAIT_OBJECT_0 + 2: //siin saame eventi, et saata tuleb
  603.         {
  604.  
  605.  
  606.  
  607.             if (SendPassword == TRUE)
  608.             {
  609.                 Wordtosend = L"coursework";
  610.  
  611.  
  612.  
  613.                 SendWordLength = wcslen(Wordtosend) * 2 + 6;
  614.                 DataBuf.len = SendWordLength;
  615.  
  616.                 *(DWORD*)DataBuf.buf = SendWordLength;
  617.  
  618.                 /*
  619.                 for (loendur1 = 0, loendur2 = 0; Wordtosend[loendur1] == 0; loendur1++, loendur2 = loendur2+2)
  620.                 {
  621.                 DataBuf.buf[loendur2 + 4] = Wordtosend[loendur1];
  622.                 }
  623.                 loendur1 = 0, loendur2 = 0;
  624.  
  625.                 while (Wordtosend[loendur1] == 0)
  626.                 {
  627.                 if(loendur1 %2)
  628.  
  629.                 }
  630.                 */
  631.  
  632.                 wcscpy(PointertoWriteWord, Wordtosend);
  633.  
  634.  
  635.                 _tprintf("Sending Password...\n");
  636.                 Result = WSASend(hClientSocket, &DataBuf, 1, &nSendBytes, 0, &SendOverlapped, NULL); // see saadab paketi
  637.                 Error = WSAGetLastError(); //Siit saame teada, kas m6ni error tuli ka saatmisega
  638.  
  639.                 if ((Error != WSA_IO_PENDING && Error != 0))
  640.                 {
  641.                     _tprintf(_T("WSASend() failed, error %d\n"), Error);
  642.                     goto out;
  643.                 }
  644.  
  645.  
  646.  
  647.                 WSAResetEvent(OutputEvents[1]);
  648.  
  649.                 SendPassword = FALSE;
  650.                 SecureConnectionEstablished = TRUE; //sellega jätame meelde, et turvaline ühendus serveriga on loodud
  651.             }
  652.             else if (SendStart == TRUE)
  653.             {
  654.                 Wordtosend = L"Start";
  655.                 SendWordLength = wcslen(Wordtosend) * 2 + 6;
  656.                 DataBuf.len = SendWordLength;
  657.                 //printf("should send start signal\n");
  658.                 *(DWORD*)DataBuf.buf = SendWordLength;
  659.                 wcscpy(PointertoWriteWord, Wordtosend);
  660.                 Result = WSASend(hClientSocket, &DataBuf, 1, &nSendBytes, 0, &SendOverlapped, NULL); // see saadab paketi
  661.                 Error = WSAGetLastError(); //Siit saame teada, kas m6ni error tuli ka saatmisega
  662.  
  663.                 if ((Error != WSA_IO_PENDING && Error != 0)) {
  664.                     _tprintf(_T("WSASend() failed, error %d\n"), Error);
  665.                     goto out;
  666.                 }
  667.  
  668.                 WSAResetEvent(OutputEvents[1]);
  669.                 SendStart = FALSE;
  670.                 ActiveDataStream = TRUE;
  671.             }
  672.             else if (SendStop == TRUE)
  673.             {
  674.                 Wordtosend = L"Stop";
  675.                 SendWordLength = wcslen(Wordtosend) * 2 + 6;
  676.                 DataBuf.len = SendWordLength;
  677.                 //printf("should send stop signal\n");
  678.                 *(DWORD*)DataBuf.buf = SendWordLength;
  679.                 wcscpy(PointertoWriteWord, Wordtosend);
  680.                 Result = WSASend(hClientSocket, &DataBuf, 1, &nSendBytes, 0, &SendOverlapped, NULL); // see saadab paketi
  681.                 Error = WSAGetLastError(); //Siit saame teada, kas m6ni error tuli ka saatmisega
  682.  
  683.                 if ((Error != WSA_IO_PENDING && Error != 0)) {
  684.                     _tprintf(_T("WSASend() failed, error %d\n"), Error);
  685.                     //goto out;
  686.                 }
  687.  
  688.                 WSAResetEvent(OutputEvents[1]);
  689.                 _tprintf("Sent STOP signal to server\n");
  690.                 SendStop = FALSE;
  691.                 //peale stoppi tuleb see thread niikuinii sulgeda
  692.                 goto out;
  693.             }
  694.  
  695.             ResetEvent(hConnectCommandGot);
  696.             break;
  697.         }
  698.  
  699.         /*
  700.         case WAIT_OBJECT_0 + 3: //tuli command nett sulgeda
  701.         {
  702.         goto out;
  703.         }
  704.         */
  705.         case WAIT_OBJECT_0 + 3:
  706.         {
  707.             _tprintf("Closing sending thread\n");
  708.  
  709.             goto out;
  710.             break;
  711.         }
  712.        
  713.         }
  714.     }
  715. out:
  716.     WSACloseEvent(OutputEvents[1]);
  717.     //ResetEvent(hCloseNetCommandGot);
  718.     //CloseHandle(hSendNet);
  719.     return 0;
  720. }
  721.  
  722. //
  723. // Function that creates connection with server
  724. //
  725. BOOL CreateConnection(void)
  726. {
  727.     BOOL Success = FALSE;
  728.  
  729.     //
  730.     // Initializations for socket
  731.     //
  732.     if (Error = WSAStartup(MAKEWORD(2, 0), &WsaData)) // Initialize Windows socket support
  733.     {
  734.         _tprintf(_T("WSAStartup() failed, error %d\n"), Error);
  735.         SocketError = TRUE;
  736.     }
  737.     else if ((hClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
  738.     {
  739.         _tprintf(_T("socket() failed, error %d\n"), WSAGetLastError());
  740.         SocketError = TRUE;
  741.     }
  742.     //
  743.     // Connect client to server
  744.     //
  745.     if (!SocketError)
  746.     {
  747.         ClientSocketInfo.sin_family = AF_INET;
  748.         ClientSocketInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
  749.         ClientSocketInfo.sin_port = htons(1234);  // port number is selected just for example
  750.         if (connect(hClientSocket, (SOCKADDR*)&ClientSocketInfo, sizeof(ClientSocketInfo)) == SOCKET_ERROR)
  751.         {
  752.             _tprintf(_T("Unable to connect to server, error %d\n"), WSAGetLastError());
  753.             SocketError = TRUE;
  754.         }
  755.     }
  756.     //
  757.     // Start net receiving thread
  758.     //
  759.     if (!SocketError)
  760.     {
  761.         if (!(hReceiveNet = (HANDLE)_beginthreadex(NULL, 0, &ReceiveNet, NULL, 0, NULL)))
  762.         {
  763.             _tprintf(_T("Unable to create socket receiving thread\n"));
  764.             Success = FALSE;
  765.         }
  766.         //
  767.         // Start net sending thread
  768.         //
  769.  
  770.         else if (!(hSendNet = (HANDLE)_beginthreadex(NULL, 0, &SendNet, NULL, 0, NULL)))
  771.         {
  772.             _tprintf(_T("Unable to create socket sending thread\n"));
  773.             Success = FALSE;
  774.         }
  775.         return TRUE;
  776.     }
  777.     else
  778.         return FALSE;
  779. }
  780.  
  781. //
  782. //function that processes incoming data and prints out
  783. //
  784. void ProcessPacket(WSABUF *Databuf)
  785. {
  786.     char *temp, *TempName;
  787.     char NumberAsString[24];
  788.     double *DoubleValue = 0;
  789.     int *IntValue = 0;
  790.     int i = 0, ChannelCounter = 0, PackageCounter = 0, nrOfPackages = 0, nrOfChannels = 0;
  791.     temp = (char*)Databuf->buf; //teen ajutise pointeri ja liigutan seda
  792.     time_t ltime; /*getting calendar time*/
  793.     ltime = time(NULL); //requesting current time
  794.     printf("Package got on : %s \n", asctime(localtime(&ltime)));
  795.  
  796.     int pkgLen = *(int *)temp; //sulgudes int castib selle korrektselt arvuks, mitte ei tee negatiivseid arve
  797.     _tprintf("%d bytes total in this packet\n", pkgLen);
  798.  
  799.     WriteFile(hFile, "Measurement packet received on: ", strlen("Measurement packet received on:\n"), &nWritten, NULL); //writing to file
  800.     WriteFile(hFile, asctime(localtime(&ltime)), strlen(asctime(localtime(&ltime))), &nWritten, NULL); //writing to file
  801.     WriteFile(hFile, "\r\n\r\n", strlen("\r\n\r\n"), &nWritten, NULL); //END OF LINE
  802.  
  803.                                                                        //teha 2 for loopi
  804.                                                                        //välimine selle jaoks, et lugeda channeleid
  805.                                                                        //sisemine selle jaoks, et lugeda objekte channelis
  806.  
  807.     nrOfChannels = *(temp + 4); //tärniga saan väärtuse
  808.     _tprintf("There are %d channels in this packet\n", nrOfChannels);
  809.     temp += 8;
  810.     for (ChannelCounter = 0; ChannelCounter < nrOfChannels; ChannelCounter++)
  811.     {
  812.         nrOfPackages = *temp; //saame teada, mitu paketti sellel channelil on
  813.         temp += 4;
  814.         printf("channel is %s\n", temp);
  815.  
  816.         WriteFile(hFile, "Measurement channel is ", strlen("Measurement channel is "), &nWritten, NULL);
  817.         WriteFile(hFile, temp, strlen(temp), &nWritten, NULL); //writing word to file
  818.         WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
  819.  
  820.         temp += strlen(temp) + 1;
  821.  
  822.         //Package counting:
  823.         for (PackageCounter = 0; PackageCounter < nrOfPackages; PackageCounter++)
  824.         {
  825.             printf("Measurement point is %s\n", temp);
  826.             WriteFile(hFile, "Measurement point is ", strlen("Measurement point is "), &nWritten, NULL);
  827.             WriteFile(hFile, temp, strlen(temp), &nWritten, NULL); //writing word to file
  828.             WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
  829.  
  830.             if (!strcmp(temp, "Temperature"))
  831.             {
  832.                 temp += strlen(temp) + 1; //liigume nimest mooda, et andmeteni j6uda
  833.                 DoubleValue = (double*)temp;
  834.                 printf("%.4f degres\n", *DoubleValue); //prindime v2lja double'i
  835.                                                        //kuna writefile kirjutab ainult stringe faili, tuleb number teha stringiks
  836.                                                        //selleks hea funktsioon sprintf()
  837.                 sprintf(NumberAsString, "%.1f °C", *DoubleValue);
  838.                 WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
  839.                 WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
  840.  
  841.                 temp += 8; //sest double omas 8 baiti, kus andmeid hoida
  842.             }
  843.             else if (!strcmp(temp, "Pressure"))
  844.             {
  845.                 temp += strlen(temp) + 1;
  846.                 DoubleValue = (double*)temp;
  847.                 printf("%.4f atm\n", *DoubleValue); //prindime v2lja double'i
  848.  
  849.                 sprintf(NumberAsString, "%.1f atm", *DoubleValue);
  850.                 WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
  851.                 WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
  852.  
  853.                 temp += 8;
  854.             }
  855.             else if (!strcmp(temp, "Level"))
  856.             {
  857.                 temp += strlen(temp) + 1;
  858.                 IntValue = (int*)temp;
  859.                 printf("%d is percentage\n", *IntValue);
  860.  
  861.                 sprintf(NumberAsString, "%d %%", *IntValue);
  862.                 WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
  863.                 WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
  864.  
  865.                 temp += 4; //ehk on oige, not sure
  866.             }
  867.             else //ülejäänud on input ja output flow
  868.             {
  869.                 temp += strlen(temp) + 1;
  870.                 DoubleValue = (double*)temp;
  871.                 printf("%.4f m/s is flow\n", *DoubleValue); //prindime v2lja double'i
  872.  
  873.                 sprintf(NumberAsString, "%.3f m³/s", *DoubleValue);
  874.                 WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
  875.                 WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
  876.  
  877.                 temp += 8;
  878.             }
  879.  
  880.         }
  881.     }
  882.  
  883.     printf("Package processed\n\n");
  884.     WriteFile(hFile, "\r\n\r\n\r\n", strlen("\r\n\r\n\r\n"), &nWritten, NULL); //DOUBLE END OF LINE
  885. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement