windows namedPipe 命名管道clent and server

时间:2023-03-09 00:50:47
windows namedPipe 命名管道clent and server

1.client:

 #include "iostream"
#include "windows.h" using namespace std;
void main(int argc,char* argv[])
{
LPCTSTR Message="the pipe's message from a client to server.";
if(argc==)
Message=argv[];
DWORD WriteNum; if(WaitNamedPipe("\\\\.\\Pipe\\Test",NMPWAIT_WAIT_FOREVER)==FALSE){
cout<<"等待链接失败!"<<endl;
return;
} HANDLE hPipe=CreateFile("\\\\.\\Pipe\\Test",GENERIC_READ|\
GENERIC_WRITE,,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(hPipe==INVALID_HANDLE_VALUE){
cout<<"管道打开失败!"<<endl;
return;
} cout<<"管道连接成功"<<endl;
if(WriteFile(hPipe,Message,strlen(Message),&WriteNum,NULL)==FALSE){
cout<<"数据写入管道失败!"<<endl;
}
CloseHandle(hPipe);
}

2.server:

 #include "iostream"
#include "windows.h"
using namespace std; void main(){
char buffer[];
DWORD ReadNum; HANDLE m_hPipe=CreateNamedPipe("\\\\.\\Pipe\\Test",PIPE_ACCESS_DUPLEX,PIPE_TYPE_BYTE|PIPE_READMODE_BYTE,,,,,NULL); if(m_hPipe==INVALID_HANDLE_VALUE)
cout<<"创建命名管道失败!"<<endl; while(){
if(ConnectNamedPipe(m_hPipe,NULL)==FALSE){
CloseHandle(m_hPipe);
cout<<"与客户机建立链接失败"<<endl;
} if(ReadFile(m_hPipe,buffer,,&ReadNum,NULL)==FALSE)
cout<<"read pipe failer!\n"<<endl; else{
buffer[ReadNum]=;
cout<<"read pipe is:"<<buffer<<".\n"<<endl;
} if(DisconnectNamedPipe(m_hPipe)==FALSE)
cout<<"终止链接失败"<<endl;
else
cout<<"成功终止链接"<<endl;
if(strcmp(buffer,"end")==)
break;
} CloseHandle(m_hPipe);
}