3.13.1 Pipe Client example


Description

This sample, read data from the pipe server and put them to worksheet directly. Here, for demo, use LT command to delay .3 seceond between read data from pipe. See Server Sample

Sample codes

#include <Origin.h>
#define PIPE_BUFFER_SIZE 1024
// if server is at a remote machine named dev4
//#define PIPENAME  "\\\\dev4\\pipe\\OriginTestPipe"
// for local server
#define PIPENAME  "\\\\.\\pipe\\OriginTestPipe" 
  
int testpipe_client(string strPipeName = PIPENAME, int nWaitLoops = 5)
{
	Worksheet wks = Project.ActiveLayer();
	if(!wks)
	{
		out_str("no active worksheet, abort.");
		return -1;
	}
	
    HANDLE hPipe; 
    string strMessage; 
    BOOL fSuccess; 
    int ii = 0;
    while(1)
    { 
        // Try to open a named pipe; wait for it, if necessary. 
        hPipe = CreateFile( 
             strPipeName, 
             GENERIC_READ | GENERIC_WRITE, 
             0,              // no sharing 
             NULL,           // no 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; 
     
        // All pipe instances are busy, so wait for 20 seconds. 
        if (!WaitNamedPipe(strPipeName, 20000) || ++ii > nWaitLoops) 
        {
            out_str("Could not open pipe " + strPipeName); 
            return -2;          
        }
    } 
    
    // The pipe connected; change to message-read mode. 
    DWORD dwMode = PIPE_READMODE_MESSAGE; 
    fSuccess = SetNamedPipeHandleState( 
      hPipe,    // pipe handle 
      &dwMode,  // new pipe mode 
      NULL,     // don't set maximum bytes 
      NULL);    // don't set maximum time 
    if (!fSuccess) 
    {
		CloseHandle(hPipe); 
        out_str("failed at SetNamedPipeHandleState"); 
        return -3;          
    }
    
	char chBuf[PIPE_BUFFER_SIZE]; 
    DWORD cbRead, cbWritten;
    
	while(1) 
    { 
        // Read from the server pipe. 
        fSuccess = ReadFile( 
             hPipe,    // pipe handle 
             chBuf,    // buffer to receive reply 
             PIPE_BUFFER_SIZE,      // size of buffer 
             &cbRead,  // number of bytes read 
             NULL);    // not overlapped 
    
        if (! fSuccess ) //nothing more to read, quit
            break; 
    
        // put data to worksheet
        wks.PasteData(chBuf);
        
        // delay .3 second 
        LT_execute("sec -p 0.3");
        
    } 
    CloseHandle(hPipe); 
    
    out_str("Done!");
    return 0; 
}