Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <Windows.h>
- #include <stdio.h>
- #include <cstdio>
- #include <conio.h>
- #include <iostream>
- #include <string>
- #include <vector>
- #include <tchar.h>
- #include "json.hpp"
- #define BUFSIZE 8092
- using namespace std;
- using json = nlohmann::json;
- // string stripper to prepare buffered data for JSON parser
- bool invalidChar(char c) {
- return !(c >= 0 && c <128);
- }
- void stripUnicode(string &str)
- {
- str.erase(remove_if(str.begin(), str.end(), invalidChar), str.end());
- }
- int _tmain(int argc, TCHAR *argv[])
- {
- vector<char> buffer;
- // named pipes parameters
- HANDLE hPipe;
- BOOL fSuccess = FALSE;
- DWORD cbToWrite, cbTotalRead=0, cbRead, dwToWrite;
- LPCTSTR lpszPipename = TEXT("\\\\.\\pipe\\JointsPipe");
- // Try to open a named pipe; wait for it, if necessary.
- while (1)
- {
- hPipe = CreateFile(
- lpszPipename, // pipe name
- GENERIC_READ | // read and write access
- GENERIC_WRITE,
- 0, // no sharing
- NULL, // default security attributes
- OPEN_EXISTING, // opens existing pipe
- 0, // default attributes
- NULL); // no template file
- // Break if the pipe handle is valid.
- if (hPipe != INVALID_HANDLE_VALUE)
- break;
- // Exit if an error other than ERROR_PIPE_BUSY occurs.
- if (GetLastError() != ERROR_PIPE_BUSY)
- {
- _tprintf(TEXT("Could not open pipe. GLE=%d\n"), GetLastError());
- return -1;
- }
- // All pipe instances are busy, so wait for 20 seconds.
- if (!WaitNamedPipe(lpszPipename, 20000))
- {
- printf("Could not open pipe: 20 second wait timed out.");
- return -1;
- }
- }
- while (1) {
- char * buf = new char[BUFSIZE];
- // -------------------------------------READING DATA
- do
- {
- fSuccess = ReadFile(hPipe, buf, BUFSIZE , &cbRead, NULL);
- cbTotalRead += cbRead; // if there is more data than standard 4096 bytes buffer, repeat reading
- if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
- break;
- buffer.insert(buffer.end(), buf, buf+cbRead);
- } while (!fSuccess);
- string sResponse = string(buffer.begin(), buffer.end());
- if (!fSuccess)
- {
- _tprintf(TEXT("ReadFile from pipe failed. GLE=%d\n"), GetLastError());
- return -1;
- }
- else {
- stripUnicode(sResponse);
- json j = sResponse.c_str(); // creating JSON object from Response string
- }
- // ------------------------------------ WRITTING DATA
- dwToWrite = sResponse.size();
- fSuccess = WriteFile(
- hPipe, // pipe handle
- buf, // message
- dwToWrite, // message length
- &cbToWrite, // bytes written
- NULL); // not overlapped
- if (!fSuccess)
- {
- _tprintf(TEXT("WriteFile to pipe failed. GLE=%d\n"), GetLastError());
- return -1;
- }
- delete[] buf;
- buffer.clear();
- sResponse.clear();
- cbTotalRead = cbToWrite = dwToWrite = 0;
- }
- FlushFileBuffers(hPipe);
- DisconnectNamedPipe(hPipe);
- CloseHandle(hPipe);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement