Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #define _WINSOCK_DEPRECATED_NO_WARNINGS
- #include "Winsock2.h" // necessary for sockets, Windows.h is not needed.
- #include "mswsock.h"
- #include "process.h" // necessary for threading
- #include "tchar.h"
- #include "time.h"
- //
- // Global variables
- //
- TCHAR CommandBuf[81];
- HANDLE hCommandGot; // event "the user has typed a command"
- HANDLE hStopCommandGot; // event "the main thread has recognized that it was the stop command"
- HANDLE hCommandProcessed; // event "the main thread has finished the processing of command"
- HANDLE hConnectCommandGot;
- HANDLE hCloseNetCommandGot;
- HANDLE hFile;
- HANDLE hReadKeyboard; // keyboard reading thread handle
- HANDLE hStdIn; // stdin standard input stream handle
- WSADATA WsaData; // filled during Winsock initialization
- DWORD Error;
- DWORD nWritten;
- SOCKET hClientSocket = INVALID_SOCKET;
- sockaddr_in ClientSocketInfo;
- HANDLE hReceiveNet; // TCP/IP info reading thread handle
- HANDLE hSendNet;
- BOOL SocketError;
- BOOL SendPassword = FALSE;
- BOOL SendStart = FALSE;
- BOOL SendStop = FALSE;
- BOOL ConnectionStatus = FALSE; //describes general status of connection
- BOOL SecureConnectionEstablished = FALSE;
- BOOL ActiveDataStream = FALSE;
- #pragma warning (disable : 4290)
- #pragma warning (disable : 4996)
- //
- // Prototypes
- //
- unsigned int __stdcall ReadKeyboard(void* pArguments);
- unsigned int __stdcall ReceiveNet(void* pArguments);
- unsigned int __stdcall SendNet(void* pArguments);
- BOOL CreateConnection(void);
- void ProcessPacket(WSABUF *Databuf);
- //****************************************************************************************************************
- // MAIN THREAD
- //****************************************************************************************************************
- int _tmain(int argc, char *argv[])
- {
- //char *logfilename = argv[1];
- //
- // opening file, was made, using file example from examples
- //
- /*
- if (argv == NULL)
- {
- printf("WTF NULL!!??\n");
- }
- */
- if (argc == 2) //kui sisestati eraldi failinimi, kuhu kirjutada
- {
- _tprintf("%s\n", argv[1]);
- hFile = CreateFile((argv[1]), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
- }
- else //muidu läheb kasutusse default failinimi
- hFile = CreateFile(("Logfile.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
- //logfilename = "Logfile.txt";
- //strcpy(logfilename, "Logfile.txt");
- if (hFile == INVALID_HANDLE_VALUE)
- {
- _tprintf(_T("Unable to create file, error %d\n"), GetLastError());
- return 1;
- }
- //
- // Initializations for multithreading
- //
- if (!(hCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
- !(hStopCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
- !(hCommandProcessed = CreateEvent(NULL, TRUE, TRUE, NULL)) ||
- !(hConnectCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
- !(hCloseNetCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)))
- {
- _tprintf(_T("CreateEvent() failed, error %d\n"), GetLastError());
- return 1;
- }
- //
- // Prepare keyboard, start the thread
- //
- hStdIn = GetStdHandle(STD_INPUT_HANDLE);
- if (hStdIn == INVALID_HANDLE_VALUE)
- {
- _tprintf(_T("GetStdHandle() failed, error %d\n"), GetLastError());
- return 1;
- }
- if (!SetConsoleMode(hStdIn, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT))
- {
- _tprintf(_T("SetConsoleMode() failed, error %d\n"), GetLastError());
- return 1;
- }
- if (!(hReadKeyboard = (HANDLE)_beginthreadex(NULL, 0, &ReadKeyboard, NULL, 0, NULL)))
- {
- _tprintf(_T("Unable to create keyboard thread\n"));
- return 1;
- }
- //ConnectionStatus = CreateConnection(); //alamfunktsioon, tekitab yhenduse
- /*
- //
- // Initializations for socket
- //
- if (Error = WSAStartup(MAKEWORD(2, 0), &WsaData)) // Initialize Windows socket support
- {
- _tprintf(_T("WSAStartup() failed, error %d\n"), Error);
- SocketError = TRUE;
- }
- else if ((hClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
- {
- _tprintf(_T("socket() failed, error %d\n"), WSAGetLastError());
- SocketError = TRUE;
- }
- //
- // Connect client to server
- //
- if (!SocketError)
- {
- ClientSocketInfo.sin_family = AF_INET;
- ClientSocketInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
- ClientSocketInfo.sin_port = htons(1234); // port number is selected just for example
- if (connect(hClientSocket, (SOCKADDR*)&ClientSocketInfo, sizeof(ClientSocketInfo)) == SOCKET_ERROR)
- {
- _tprintf(_T("Unable to connect to server, error %d\n"), WSAGetLastError());
- SocketError = TRUE;
- }
- }
- //
- // Start net receiving thread
- //
- if (!SocketError)
- {
- if (!(hReceiveNet = (HANDLE)_beginthreadex(NULL, 0, &ReceiveNet, NULL, 0, NULL)))
- {
- _tprintf(_T("Unable to create socket receiving thread\n"));
- goto out;
- }
- //
- // Start net sending thread
- //
- if (!(hSendNet = (HANDLE)_beginthreadex(NULL, 0, &SendNet, NULL, 0, NULL)))
- {
- _tprintf(_T("Unable to create socket sending thread\n"));
- goto out;
- }
- }
- */
- //
- // Main processing loop
- //
- while (TRUE)
- {
- if (WaitForSingleObject(hCommandGot, INFINITE) != WAIT_OBJECT_0)
- { // Wait until the command has arrived (i.e. until CommandGot is signaled)
- _tprintf(_T("WaitForSingleObject() failed, error %d\n"), GetLastError());
- goto out;
- }
- ResetEvent(hCommandGot); // CommandGot back to unsignaled
- if (!_tcsicmp(CommandBuf, _T("exit"))) // Case-insensitive comparation
- {
- SetEvent(hStopCommandGot); // To force the other threads to quit
- break;
- }
- else if (!_tcsicmp(CommandBuf, _T("connect"))) // tuleb connectimis command
- {
- _tprintf("Command connect accepted\n");
- if (SecureConnectionEstablished == FALSE)
- {
- if (ConnectionStatus == FALSE || SendPassword == FALSE)
- {
- ConnectionStatus = CreateConnection();
- if (ConnectionStatus == FALSE) //ehk ühendust ei õnnestunud luua, sulgeme threadid ka
- {
- SetEvent(hCloseNetCommandGot);
- if (hReceiveNet)
- {
- WaitForSingleObject(hReceiveNet, INFINITE); // Wait until the end of receive thread
- CloseHandle(hReceiveNet);
- }
- if (hSendNet)
- {
- WaitForSingleObject(hSendNet, INFINITE); // Wait until the end of receive thread
- CloseHandle(hSendNet);
- }
- ResetEvent(hCloseNetCommandGot);
- if (hClientSocket != INVALID_SOCKET)
- {
- if (shutdown(hClientSocket, SD_RECEIVE) == SOCKET_ERROR)
- {
- if ((Error = WSAGetLastError()) != WSAENOTCONN) // WSAENOTCONN means that the connection was not established,
- // so the shut down was senseless
- _tprintf(_T("shutdown() failed, error %d\n"), WSAGetLastError());
- }
- closesocket(hClientSocket);
- }
- WSACleanup(); // clean Windows sockets support
- SocketError = FALSE;
- }
- }
- else
- {
- _tprintf("Establishing secure connection\n");
- SetEvent(hConnectCommandGot); //event, et connect käsk anti käiku
- }
- }
- else
- {
- _tprintf("Secure connection has already been made\n");
- }
- SetEvent(hCommandProcessed); //event, et käsu täitmine on lõppenud
- }
- else if (!_tcsicmp(CommandBuf, _T("start"))) // tuleb connectimis command
- {
- _tprintf("Command start accepted\n");
- if (ConnectionStatus == TRUE)
- {
- if (ActiveDataStream == FALSE)
- {
- SetEvent(hConnectCommandGot); //event, et connect käsk anti käiku
- SendStart = TRUE;
- SetEvent(hCommandProcessed); //event, et käsu täitmine on lõppenud
- }
- }
- else
- _tprintf("Connection not established yet, try connect instead\n");
- SetEvent(hCommandProcessed);
- }
- else if (!_tcsicmp(CommandBuf, _T("break"))) // tuleb connectimis command
- {
- _tprintf("Command break accepted\n");
- if (ActiveDataStream == TRUE)
- {
- ActiveDataStream = FALSE;
- SendStart = FALSE;
- //event, et käsu täitmine on lõppenud
- }
- else
- _tprintf("Active connection is already down\n");
- SetEvent(hCommandProcessed);
- }
- else if (!_tcsicmp(CommandBuf, _T("stop"))) // Case-insensitive comparation
- {
- //_tprintf("Command Stop Accepted, nothing to do yet\n");
- //SetEvent(hCloseNetCommandGot);
- if (ConnectionStatus == TRUE || SecureConnectionEstablished == TRUE)
- {
- _tprintf("Closing connection\n");
- SendStop = TRUE;
- SetEvent(hConnectCommandGot);
- /*
- while (SendStop == TRUE)
- {
- _tprintf("waiting for sending thread to send stop message\n");
- }
- */
- SetEvent(hCloseNetCommandGot);
- if (hReceiveNet)
- {
- WaitForSingleObject(hReceiveNet, INFINITE); // Wait until the end of receive thread
- CloseHandle(hReceiveNet);
- }
- if (hSendNet)
- {
- WaitForSingleObject(hSendNet, INFINITE); // Wait until the end of receive thread
- CloseHandle(hSendNet);
- }
- //_tprintf("Closing connection 2\n");
- /*
- if (hClientSocket != INVALID_SOCKET)
- {
- if (shutdown(hClientSocket, SD_RECEIVE) == SOCKET_ERROR)
- {
- if ((Error = WSAGetLastError()) != WSAENOTCONN) // WSAENOTCONN means that the connection was not established,
- // so the shut down was senseless
- _tprintf(_T("shutdown() failed, error %d\n"), WSAGetLastError());
- }
- closesocket(hClientSocket);
- }
- */
- //WSACleanup(); //Vajalik windows socketis oleva kama puhastamiseks
- ConnectionStatus = FALSE;
- SecureConnectionEstablished = FALSE;
- ActiveDataStream = FALSE;
- ResetEvent(hCloseNetCommandGot);
- }
- else
- _tprintf("Connection is already down\n");
- SetEvent(hCommandProcessed);
- }
- else
- {
- _tprintf(_T("Command \"%s\" not recognized\n"), CommandBuf);
- SetEvent(hCommandProcessed); // To allow the keyboard reading thread to continue
- }
- }
- //
- // Shut down
- //
- out:
- if (hReadKeyboard)
- {
- WaitForSingleObject(hReadKeyboard, INFINITE); // Wait until the end of keyboard thread
- CloseHandle(hReadKeyboard);
- }
- if (hReceiveNet)
- {
- WaitForSingleObject(hReceiveNet, INFINITE); // Wait until the end of receive thread
- CloseHandle(hReceiveNet);
- }
- if (hSendNet)
- {
- WaitForSingleObject(hSendNet, INFINITE); // Wait until the end of receive thread
- CloseHandle(hSendNet);
- }
- if (hClientSocket != INVALID_SOCKET)
- {
- if (shutdown(hClientSocket, SD_RECEIVE) == SOCKET_ERROR)
- {
- if ((Error = WSAGetLastError()) != WSAENOTCONN) // WSAENOTCONN means that the connection was not established,
- // so the shut down was senseless
- _tprintf(_T("shutdown() failed, error %d\n"), WSAGetLastError());
- }
- closesocket(hClientSocket);
- }
- WSACleanup(); // clean Windows sockets support
- CloseHandle(hStopCommandGot);
- CloseHandle(hCommandGot);
- CloseHandle(hCommandProcessed);
- CloseHandle(hConnectCommandGot);
- CloseHandle(hCloseNetCommandGot);
- CloseHandle(hFile); //closing file at the end of program cycle
- return 0;
- }
- //**************************************************************************************************************
- // KEYBOARD READING THREAD
- //**************************************************************************************************************
- unsigned int __stdcall ReadKeyboard(void* pArguments)
- {
- DWORD nReadChars;
- HANDLE KeyboardEvents[2];
- KeyboardEvents[1] = hCommandProcessed;
- KeyboardEvents[0] = hStopCommandGot;
- DWORD WaitResult;
- //
- // Reading loop
- //
- while (TRUE)
- {
- WaitResult = WaitForMultipleObjects(2, KeyboardEvents,
- FALSE, // wait until one of the events becomes signaled
- INFINITE);
- // Waiting until hCommandProcessed or hStopCommandGot becomes signaled. Initially hCommandProcessed
- // is signaled, so at the beginning WaitForMultipleObjects() returns immediately with WaitResult equal
- // with WAIT_OBJECT_0 + 1.
- if (WaitResult == WAIT_OBJECT_0)
- return 0; // Stop command, i.e. hStopCommandGot is signaled
- else if (WaitResult == WAIT_OBJECT_0 + 1)
- { // If the signaled event is hCommandProcessed, the WaitResult is WAIT_OBJECT_0 + 1
- _tprintf(_T("Insert command\n"));
- if (!ReadConsole(hStdIn, CommandBuf, 80, &nReadChars, NULL))
- { // The problem is that when we already are in this function, the only way to leave it
- // is to type something and then press ENTER. So we cannot step into this function at any moment.
- // WaitForMultipleObjects() prevents it.
- _tprintf(_T("ReadConsole() failed, error %d\n"), GetLastError());
- return 1;
- }
- CommandBuf[nReadChars - 2] = 0; // The command in buf ends with "\r\n", we have to get rid of them
- ResetEvent(hCommandProcessed);
- // Set hCommandProcessed to non-signaled. Therefore WaitForMultipleObjects() blocks the keyboard thread.
- // When the main thread has ended the analyzing of command, it sets hCommandprocessed or hStopCommandGot
- // to signaled and the keyboard thread can continue.
- SetEvent(hCommandGot);
- // Set hCommandGot event to signaled. Due to that WaitForSingleObject() in the main thread
- // returns, the waiting stops and the analyzing of inserted command may begin
- }
- else
- { // waiting failed
- _tprintf(_T("WaitForMultipleObjects()failed, error %d\n"), GetLastError());
- return 1;
- }
- }
- return 0;
- }
- //********************************************************************************************************************
- // TCP/IP INFO RECEIVING THREAD
- //********************************************************************************************************************
- unsigned int __stdcall ReceiveNet(void* pArguments)
- {
- //
- // Preparations
- //
- WSABUF DataBuf; // Buffer for received data is a structure
- char ArrayInBuf[2048];
- DataBuf.buf = &ArrayInBuf[0];
- DataBuf.len = 2048;
- DWORD nReceivedBytes = 0, ReceiveFlags = 0;
- HANDLE NetEvents[3];
- NetEvents[2] = hCloseNetCommandGot;
- NetEvents[0] = hStopCommandGot;
- WSAOVERLAPPED Overlapped;
- memset(&Overlapped, 0, sizeof Overlapped);
- Overlapped.hEvent = NetEvents[1] = WSACreateEvent(); // manual and nonsignaled
- DWORD Result, Error;
- wchar_t *DataPointer;
- wchar_t *identifier = L"Identify";
- wchar_t *accepter = L"Accepted";
- //
- // Receiving loop
- //
- while (TRUE)
- {
- Result = WSARecv(hClientSocket,
- &DataBuf,
- 1, // no comments here
- &nReceivedBytes,
- &ReceiveFlags, // no comments here
- &Overlapped,
- NULL); // no comments here
- if (Result == SOCKET_ERROR)
- { // Returned with socket error, let us examine why
- if ((Error = WSAGetLastError()) != WSA_IO_PENDING)
- { // Unable to continue, for example because the server has closed the connection
- _tprintf(_T("WSARecv() failed, error %d\n"), Error);
- goto out;
- }
- DWORD WaitResult = WSAWaitForMultipleEvents(3, NetEvents, FALSE, WSA_INFINITE, FALSE); // wait for data
- switch (WaitResult) // analyse why the waiting ended
- {
- case WAIT_OBJECT_0: // Waiting stopped because hStopCommandGot has become signaled, i.e. the user has decided to exit
- goto out;
- break;
- case WAIT_OBJECT_0 + 1:
- // Waiting stopped because Overlapped.hEvent is now signaled, i.e. the receiving operation has ended.
- // Now we have to see how many bytes we have got.
- WSAResetEvent(NetEvents[1]); // to be ready for the next data package
- if (WSAGetOverlappedResult(hClientSocket, &Overlapped, &nReceivedBytes, FALSE, &ReceiveFlags))
- {
- _tprintf(_T("%d bytes received\n"), nReceivedBytes);
- // Here should follow the processing of received data
- DataPointer = (wchar_t*)(DataBuf.buf + 4);
- //_tprintf(_T("%ls\n"), DataPointer);
- if (!wcscmp(DataPointer, identifier)) //detectime, kas sisendiks tuli Identify
- {
- _tprintf("Identity detected, use connect command again\n");
- //siia peaks tulema event, et saatja saadaks parooli
- //SetEvent(hSendCommandGot);
- SendPassword = TRUE;
- SetEvent(hConnectCommandGot);
- }
- else if (!wcscmp(DataPointer, accepter))
- {
- _tprintf("Secure connection Established\n");
- }
- else
- {
- _tprintf("Got packet!\n");
- ProcessPacket(&DataBuf);
- }
- if (ActiveDataStream == TRUE)
- {
- //siia tuleb sissetulnud data processimine
- SetEvent(hConnectCommandGot); //palume uue paketi saata
- SendStart = TRUE;
- }
- break;
- }
- else
- { // Fatal problems
- _tprintf(_T("WSAGetOverlappedResult() failed, error %d\n"), GetLastError());
- goto out;
- break;
- }
- /*
- case WAIT_OBJECT_0 + 2: //tuli command neti sulgemiseks
- goto out;
- */
- case WAIT_OBJECT_0 + 2:
- {
- _tprintf("Closing receiving net thread\n");
- goto out;
- break;
- }
- default: // Fatal problems
- _tprintf(_T("WSAWaitForMultipleEvents() failed in receiving thread, error %d\n"), WSAGetLastError());
- goto out;
- }
- }
- else
- { // Returned immediately without socket error
- if (!nReceivedBytes)
- { // When the receiving function has read nothing and returned immediately, the connection is off
- _tprintf(_T("Server has closed the connection\n"));
- goto out;
- }
- else
- {
- _tprintf(_T("%d bytes received\n"), nReceivedBytes);
- // Here should follow the processing of received data
- }
- }
- }
- out:
- WSACloseEvent(NetEvents[1]);
- return 0;
- }
- //********************************************************************************************************************
- // TCP/IP INFO SENDING THREAD
- //********************************************************************************************************************
- /*
- thread will use WSASend function to send data
- */
- unsigned int __stdcall SendNet(void* pArguments)
- {
- WSABUF DataBuf;
- DWORD Result, Error, nSendBytes = 0, SendFlags = 0;
- char ArrayOutBuf[1024];
- DataBuf.buf = &ArrayOutBuf[0];
- DataBuf.len = strlen(ArrayOutBuf);
- wchar_t *Wordtosend;
- wchar_t *PointertoWriteWord = (wchar_t*)DataBuf.buf + 2;
- DWORD SendWordLength;
- HANDLE OutputEvents[4];
- OutputEvents[0] = hStopCommandGot; //sending operation cancelling
- OutputEvents[2] = hConnectCommandGot;
- OutputEvents[3] = hCloseNetCommandGot;
- WSAOVERLAPPED SendOverlapped;
- //_tprintf("Oleme saatmise thread'i joudnud\n");
- SendOverlapped.hEvent = OutputEvents[1] = WSACreateEvent(); // manual and nonsignaled
- while (TRUE)
- {
- //_tprintf("ootame saatmise k2sku...\n");
- DWORD WaitResult = WaitForMultipleObjects(4, OutputEvents, FALSE, INFINITE);
- switch (WaitResult) //vastavalt sellele, mis hetkel waitresult on, on tegevus
- {
- case WAIT_OBJECT_0: //siin lahkume threadist e. tulnud on event Stop
- {
- goto out;
- break;
- }
- case WAIT_OBJECT_0 + 1:
- {
- WSAResetEvent(OutputEvents[1]);
- //goto out;
- }
- case WAIT_OBJECT_0 + 2: //siin saame eventi, et saata tuleb
- {
- if (SendPassword == TRUE)
- {
- Wordtosend = L"coursework";
- SendWordLength = wcslen(Wordtosend) * 2 + 6;
- DataBuf.len = SendWordLength;
- *(DWORD*)DataBuf.buf = SendWordLength;
- /*
- for (loendur1 = 0, loendur2 = 0; Wordtosend[loendur1] == 0; loendur1++, loendur2 = loendur2+2)
- {
- DataBuf.buf[loendur2 + 4] = Wordtosend[loendur1];
- }
- loendur1 = 0, loendur2 = 0;
- while (Wordtosend[loendur1] == 0)
- {
- if(loendur1 %2)
- }
- */
- wcscpy(PointertoWriteWord, Wordtosend);
- _tprintf("Sending Password...\n");
- Result = WSASend(hClientSocket, &DataBuf, 1, &nSendBytes, 0, &SendOverlapped, NULL); // see saadab paketi
- Error = WSAGetLastError(); //Siit saame teada, kas m6ni error tuli ka saatmisega
- if ((Error != WSA_IO_PENDING && Error != 0))
- {
- _tprintf(_T("WSASend() failed, error %d\n"), Error);
- goto out;
- }
- WSAResetEvent(OutputEvents[1]);
- SendPassword = FALSE;
- SecureConnectionEstablished = TRUE; //sellega jätame meelde, et turvaline ühendus serveriga on loodud
- }
- else if (SendStart == TRUE)
- {
- Wordtosend = L"Start";
- SendWordLength = wcslen(Wordtosend) * 2 + 6;
- DataBuf.len = SendWordLength;
- //printf("should send start signal\n");
- *(DWORD*)DataBuf.buf = SendWordLength;
- wcscpy(PointertoWriteWord, Wordtosend);
- Result = WSASend(hClientSocket, &DataBuf, 1, &nSendBytes, 0, &SendOverlapped, NULL); // see saadab paketi
- Error = WSAGetLastError(); //Siit saame teada, kas m6ni error tuli ka saatmisega
- if ((Error != WSA_IO_PENDING && Error != 0)) {
- _tprintf(_T("WSASend() failed, error %d\n"), Error);
- goto out;
- }
- WSAResetEvent(OutputEvents[1]);
- SendStart = FALSE;
- ActiveDataStream = TRUE;
- }
- else if (SendStop == TRUE)
- {
- Wordtosend = L"Stop";
- SendWordLength = wcslen(Wordtosend) * 2 + 6;
- DataBuf.len = SendWordLength;
- //printf("should send stop signal\n");
- *(DWORD*)DataBuf.buf = SendWordLength;
- wcscpy(PointertoWriteWord, Wordtosend);
- Result = WSASend(hClientSocket, &DataBuf, 1, &nSendBytes, 0, &SendOverlapped, NULL); // see saadab paketi
- Error = WSAGetLastError(); //Siit saame teada, kas m6ni error tuli ka saatmisega
- if ((Error != WSA_IO_PENDING && Error != 0)) {
- _tprintf(_T("WSASend() failed, error %d\n"), Error);
- //goto out;
- }
- WSAResetEvent(OutputEvents[1]);
- _tprintf("Sent STOP signal to server\n");
- SendStop = FALSE;
- //peale stoppi tuleb see thread niikuinii sulgeda
- goto out;
- }
- ResetEvent(hConnectCommandGot);
- break;
- }
- /*
- case WAIT_OBJECT_0 + 3: //tuli command nett sulgeda
- {
- goto out;
- }
- */
- case WAIT_OBJECT_0 + 3:
- {
- _tprintf("Closing sending thread\n");
- goto out;
- break;
- }
- }
- }
- out:
- WSACloseEvent(OutputEvents[1]);
- //ResetEvent(hCloseNetCommandGot);
- //CloseHandle(hSendNet);
- return 0;
- }
- //
- // Function that creates connection with server
- //
- BOOL CreateConnection(void)
- {
- BOOL Success = FALSE;
- //
- // Initializations for socket
- //
- if (Error = WSAStartup(MAKEWORD(2, 0), &WsaData)) // Initialize Windows socket support
- {
- _tprintf(_T("WSAStartup() failed, error %d\n"), Error);
- SocketError = TRUE;
- }
- else if ((hClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
- {
- _tprintf(_T("socket() failed, error %d\n"), WSAGetLastError());
- SocketError = TRUE;
- }
- //
- // Connect client to server
- //
- if (!SocketError)
- {
- ClientSocketInfo.sin_family = AF_INET;
- ClientSocketInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
- ClientSocketInfo.sin_port = htons(1234); // port number is selected just for example
- if (connect(hClientSocket, (SOCKADDR*)&ClientSocketInfo, sizeof(ClientSocketInfo)) == SOCKET_ERROR)
- {
- _tprintf(_T("Unable to connect to server, error %d\n"), WSAGetLastError());
- SocketError = TRUE;
- }
- }
- //
- // Start net receiving thread
- //
- if (!SocketError)
- {
- if (!(hReceiveNet = (HANDLE)_beginthreadex(NULL, 0, &ReceiveNet, NULL, 0, NULL)))
- {
- _tprintf(_T("Unable to create socket receiving thread\n"));
- Success = FALSE;
- }
- //
- // Start net sending thread
- //
- else if (!(hSendNet = (HANDLE)_beginthreadex(NULL, 0, &SendNet, NULL, 0, NULL)))
- {
- _tprintf(_T("Unable to create socket sending thread\n"));
- Success = FALSE;
- }
- return TRUE;
- }
- else
- return FALSE;
- }
- //
- //function that processes incoming data and prints out
- //
- void ProcessPacket(WSABUF *Databuf)
- {
- char *temp, *TempName;
- char NumberAsString[24];
- double *DoubleValue = 0;
- int *IntValue = 0;
- int i = 0, ChannelCounter = 0, PackageCounter = 0, nrOfPackages = 0, nrOfChannels = 0;
- temp = (char*)Databuf->buf; //teen ajutise pointeri ja liigutan seda
- time_t ltime; /*getting calendar time*/
- ltime = time(NULL); //requesting current time
- printf("Package got on : %s \n", asctime(localtime(<ime)));
- int pkgLen = *(int *)temp; //sulgudes int castib selle korrektselt arvuks, mitte ei tee negatiivseid arve
- _tprintf("%d bytes total in this packet\n", pkgLen);
- WriteFile(hFile, "Measurement packet received on: ", strlen("Measurement packet received on:\n"), &nWritten, NULL); //writing to file
- WriteFile(hFile, asctime(localtime(<ime)), strlen(asctime(localtime(<ime))), &nWritten, NULL); //writing to file
- WriteFile(hFile, "\r\n\r\n", strlen("\r\n\r\n"), &nWritten, NULL); //END OF LINE
- //teha 2 for loopi
- //välimine selle jaoks, et lugeda channeleid
- //sisemine selle jaoks, et lugeda objekte channelis
- nrOfChannels = *(temp + 4); //tärniga saan väärtuse
- _tprintf("There are %d channels in this packet\n", nrOfChannels);
- temp += 8;
- for (ChannelCounter = 0; ChannelCounter < nrOfChannels; ChannelCounter++)
- {
- nrOfPackages = *temp; //saame teada, mitu paketti sellel channelil on
- temp += 4;
- printf("channel is %s\n", temp);
- WriteFile(hFile, "Measurement channel is ", strlen("Measurement channel is "), &nWritten, NULL);
- WriteFile(hFile, temp, strlen(temp), &nWritten, NULL); //writing word to file
- WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
- temp += strlen(temp) + 1;
- //Package counting:
- for (PackageCounter = 0; PackageCounter < nrOfPackages; PackageCounter++)
- {
- printf("Measurement point is %s\n", temp);
- WriteFile(hFile, "Measurement point is ", strlen("Measurement point is "), &nWritten, NULL);
- WriteFile(hFile, temp, strlen(temp), &nWritten, NULL); //writing word to file
- WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
- if (!strcmp(temp, "Temperature"))
- {
- temp += strlen(temp) + 1; //liigume nimest mooda, et andmeteni j6uda
- DoubleValue = (double*)temp;
- printf("%.4f degres\n", *DoubleValue); //prindime v2lja double'i
- //kuna writefile kirjutab ainult stringe faili, tuleb number teha stringiks
- //selleks hea funktsioon sprintf()
- sprintf(NumberAsString, "%.1f °C", *DoubleValue);
- WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
- WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
- temp += 8; //sest double omas 8 baiti, kus andmeid hoida
- }
- else if (!strcmp(temp, "Pressure"))
- {
- temp += strlen(temp) + 1;
- DoubleValue = (double*)temp;
- printf("%.4f atm\n", *DoubleValue); //prindime v2lja double'i
- sprintf(NumberAsString, "%.1f atm", *DoubleValue);
- WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
- WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
- temp += 8;
- }
- else if (!strcmp(temp, "Level"))
- {
- temp += strlen(temp) + 1;
- IntValue = (int*)temp;
- printf("%d is percentage\n", *IntValue);
- sprintf(NumberAsString, "%d %%", *IntValue);
- WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
- WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
- temp += 4; //ehk on oige, not sure
- }
- else //ülejäänud on input ja output flow
- {
- temp += strlen(temp) + 1;
- DoubleValue = (double*)temp;
- printf("%.4f m/s is flow\n", *DoubleValue); //prindime v2lja double'i
- sprintf(NumberAsString, "%.3f m³/s", *DoubleValue);
- WriteFile(hFile, NumberAsString, strlen(NumberAsString), &nWritten, NULL); //writing word to file
- WriteFile(hFile, "\r\n", strlen("\r\n"), &nWritten, NULL); //END OF LINE
- temp += 8;
- }
- }
- }
- printf("Package processed\n\n");
- WriteFile(hFile, "\r\n\r\n\r\n", strlen("\r\n\r\n\r\n"), &nWritten, NULL); //DOUBLE END OF LINE
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement