c++事件及管道通信

事件通信:

事件通信主要是发送信号,作为事件通知使用,占用资源少,速度快

 发送端:

hEvent = ::CreateEvent(NULL,TRUE,FALSE,_T("MYMESSAGE"));
if ((hEvent == INVALID_HANDLE_VALUE) || (hEvent == 0)) {
    AfxMessageBox(L"start error");
}
SetEvent(hsEvent);

接收端:

HANDLE g_hEvent = ::OpenEvent(EVENT_ALL_ACCESS, FALSE, _T("MYMESSAGE"));
if((g_hEvent == INVALID_HANDLE_VALUE) || (g_hEvent == 0)){
    AfxMessageBox(L"open error!");
}
while(1)
{
    if(WaitForSingleObject(g_hEvent, 100) == WAIT_OBJECT_0)
    {
       AfxMessageBox(L"recevice finished!");
       ResetEvent(g_hEvent);
    }
}


管道通信:

管理通信功能是发跨进程发送二进制消息内容,打开关闭等消耗资源多

客户端:

HANDLE m_hPipeToMain = CreateFile(L"\\\\.\\pipe\\Dbtest800Pipe", 
		GENERIC_WRITE|GENERIC_READ,
                  0,
                  NULL,
                  OPEN_EXISTING,
                  0,
                  NULL);
//GENERIC_WRITE|GENERIC_READ表示可读可写	
if (pipe!=0 || pipe == INVALID_HANDLE_VALUE) {
    DWORD dwWrite;
    char szPipeUpdate[200] = "send message form client";
    WriteFile(m_hPipeToMain, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);
    AfxMessageBox(L"send pipe success");
    CloseHandle(pipe);
}else{
   MessageBox(L"ERROR");
}


服务端:

HANDLE hPipe = CreateNamedPipeW(L"\\\\.\\pipe\\Dbtest800Pipe",
				PIPE_ACCESS_DUPLEX,
				PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
				PIPE_UNLIMITED_INSTANCES,
				BUFSIZE,
				BUFSIZE,
				PIPE_TIMEOUT,
				NULL);

//PIPE_ACCESS_DUPLEX 表示可读可写
if (hPipe == INVALID_HANDLE_VALUE) {
     AfxMessageBox(L"create pipe fail");
 }

if (ConnectNamedPipe(hPipe, NULL) || (GetLastError() == ERROR_PIPE_CONNECTED)) {
    DWORD cbBytesRead;
    char chRequest[BUFSIZE];
    bool fSuccess = ReadFile (hPipe, chRequest, BUFSIZE, &cbBytesRead, NULL);
    chRequest[cbBytesRead] = '\0';
    AfxMessageBox(CString(chRequest));
    if (! fSuccess || cbBytesRead == 0) {
        break;
    }
    DisconnectNamedPipe(hPipe);
} else {
   CloseHandle(hPipe);
   AfxMessageBox(L"close");
}
CloseHandle(hPipe);



 

你可能感兴趣的:(c++)