来自客户端(您的服务)和服务器(通知程序)的一些简单的 sn-ps
[注意:这是改编自我不久前完成的一个项目,而该项目又受到来自 CreateNamedPipe & co 的 MSDN 示例的严重“影响”]:
服务器端:
HANDLE hPipe = INVALID_HANDLE_VALUE;
bool bConnected = false;
hPipe = CreateNamedPipe( L"\\\\.\\pipe\\nhsupspipe",
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
sizeof( Message ),
0,
0,
NULL );
// failed to create pipe?
if( hPipe == INVALID_HANDLE_VALUE ){
return -1;
}
// Wait for the client to connect; if it succeeds,
// the function returns a nonzero value. If the function
// returns zero, GetLastError returns ERROR_PIPE_CONNECTED.
bConnected = ConnectNamedPipe( hPipe, NULL ) ? true : ( GetLastError() == ERROR_PIPE_CONNECTED );
if( bConnected ){
while( true ){
unsigned long ulBytesRead = 0;
// read client requests from the pipe.
bool bReadOk = ReadFile( hPipe,
&message,
sizeof( message ),
&ulBytesRead,
NULL );
// bail if read failed [error or client closed connection]
if( !bReadOk || ulBytesRead == 0 )
break;
// all ok, process the message received
}
}
else{
// the client could not connect, so close the pipe.
CloseHandle( hPipe );
}
return 0;
客户:
HANDLE hPipe = INVALID_HANDLE_VALUE;
// create the named pipe handle
hPipe = CreateFile( L"\\\\.\\pipe\\nhsupspipe",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL );
// if everything ok set mode to message mode
if( INVALID_HANDLE_VALUE != hPipe ){
DWORD dwMode = PIPE_READMODE_MESSAGE;
// if this fails bail out
if( !SetNamedPipeHandleState( hPipe, &dwMode, NULL, NULL ) ){
CloseHandle( hPipe );
return -1;
}
}
unsigned long ulBytesWritten = 0;
bool bWriteOk = WriteFile( hPipe,
( LPCVOID )&message,
sizeof( Message ),
&ulBytesWritten,
NULL );
// check if the writing was ok
if( !bWriteOk || ulBytesWritten < sizeof( Message ) ){
return -1;
}
// written ok
return 0;
上面提到的Message是一个结构,它将成为您的消息,您可能想要pack。
由于在您的场景中,客户端(服务)可能会在服务器(通知程序)之前启动并运行,因此您需要在客户端制定某种重新连接策略。
另外,你应该仔细考虑奥斯特曼先生在他的reply 中所说的话(即使没有别的,因为他是拉里奥斯特曼)。