3.13.2 Pipe Server example
Description
This sample read data file "gamma.dat" come with Origin, and send to local "OriginTestPipe" pipe. Here use "LT_execute("sec -p 1");" as time delay to simulate sending a data to pipe every second. See Client Sample
Sameple codes
#include <Origin.h>
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Start your functions here.
#define PIPE_TIMEOUT 10000
#define BUFSIZE 10000
#define PIPENAME "\\\\.\\pipe\\OriginTestPipe"
//err will just printf in this function so just return void
static void do_pipe_process(HANDLE hPipe, string strFileName = "Samples\\Curve Fitting\\gamma.dat")
{
stdioFile ff;
string strFilename = GetAppPath(TRUE) + strFileName;
bool bRet = ff.Open(strFilename, file::modeRead);
if(!bRet)
{
out_str(strFilename + " not found!");
return;
}
printf("Pipe handle = %X\nHit Escape to abort!\nSending Data..\n", (int)hPipe);
waitCursor cur;
string strTemp;
int ii=0;
while(!cur.CheckEsc() && ff.ReadString(strTemp))
{
DWORD nWritten, nBytes = strTemp.GetLength()+1;
LPSTR lpbuff = strTemp.GetBuffer(nBytes);
out_str(lpbuff); // show locally to script window
BOOL bSuccess = WriteFile(
hPipe, // handle to pipe
lpbuff, // buffer to write from
nBytes, // number of bytes to write
&nWritten, // number of bytes written
NULL); // not overlapped I/O
if (! bSuccess || nBytes != nWritten)
{
printf("success=%d, %d bytes written out of %d\n", bSuccess, nWritten, nBytes);
break;
}
// just simulate the speed of slow external hardware data generator
// delay 1 sec,
LT_execute("sec -p 1");
}
ff.Close();
out_str("END!");
}
int testpipserver()
{
BOOL bConnected;
HANDLE hPipe;
// create named pipe
hPipe = CreateNamedPipe(
PIPENAME, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
BUFSIZE, // output buffer size
BUFSIZE, // input buffer size
PIPE_TIMEOUT, // client time-out
NULL); // no security attribute
if (hPipe == INVALID_HANDLE_VALUE)
{
out_str("Could not CreatePipe: " + PIPENAME);
return -1;
}
printf("%s is setup, waiting for client request.\n", PIPENAME);
if(ConnectNamedPipe(hPipe, NULL))
{
do_pipe_process(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
}
else
{
// The client could not connect, so close the pipe.
out_str("failed in connect!");
CloseHandle(hPipe);
return -1;
}
return 0;
}
|