管道可以实现本地和网络上两个进程的通信
服务器端:
::OnPipeCreate() //创建命名管道
{
hPipe = CreateNamedPipe("\\\\.\\pipe\\MyPipe",PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
0,1,1024,1024,0,NULL);
if(INVALID_HANDLE_VALUE == hPipe) //hPipe为一个全局句柄
{
AfxMessageBox("操作失败!");
hPipe = NULL;
return;
}
HANDLE hEvent;
hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
if(!hEvent)
{
AfxMessageBox("创建事件对象失败!");
CloseHandle(hPipe);
hPipe = NULL;
return;
}
OVERLAPPED ovlap;
ZeroMemory(&ovlap,sizeof(OVERLAPPED));
ovlap.hEvent = hEvent;
if(!ConnectNamedPipe(hPipe,&ovlap))
{
if(ERROR_IO_PENDING != GetLastError())
{
AfxMessageBox("等待客户端连接失败!");
CloseHandle(hPipe);
CloseHandle(hEvent);
hPipe = NULL;
return;
}
}
if(WAIT_FAILED == WaitForSingleObject(hEvent,INFINITE))
{
AfxMessageBox("等待对象失败!");
CloseHandle(hPipe);
CloseHandle(hEvent);
hPipe = NULL;
return;
}
CloseHandle(hEvent);
}
::OnPipeRead() //读管道数据
{
char buf[100];
DWORD dwRead;
if(!ReadFile(hPipe,buf,100,&dwRead,NULL))
{
AfxMessageBox("操作失败!");
return;
}
}
::OnPipeWrite() //写管道数据
{
char buf[] = "";
DWORD dwWrite;
if(!WriteFile(hPipe,buf,strlen(buf)+1,&dwWrite,NULL))
{
AfxMessageBox("操作失败!");
return;
}
}
客户端:
::OnPipeConnect(CString hostName)//连接管道 ,hostName为主机名
{
CString pipeName("");
pipeName.Format("\\\\%s\\pipe\\MyPipe",hostName);
if(!WaitNamedPipe(pipeName,NMPWAIT_WAIT_FOREVER))
{
AfxMessageBox("连接失败!");
return;
}
hPipe = CreateFile(pipeName,GENERIC_READ | GENERIC_WRITE,
0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(INVALID_HANDLE_VALUE == hPipe)
{
AfxMessageBox("操作失败!");
hPipe = NULL;
return;
}
}
读取和写入管道程序 和服务器端一样