命名管道通信服务器和客户端创建
服务器程序:(以C++Builder为例)
void __fastcall ServerThread::Execute() { wchar_t *pipeName = L"\\\\.\\pipe\\testpipe"; pipe_handle = CreateNamedPipe(pipeName, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 1024, 1024, 1000, NULL); if(pipe_handle == INVALID_HANDLE_VALUE) { ShowMessage(L"通道创建失败"); return; } ShowMessage(L"通道创建成功"); //--------------------------进入阻塞状态,等待客户端响应--------------------------------- if(ConnectNamedPipe(pipe_handle, NULL)) { ShowMessage(L"服务器成功响应客户端"); } else { ShowMessage(L"服务器成功响应客户端失败"); CloseHandle(pipe_handle); } }
消息的发送:
void __fastcall TForm1::Button2Click(TObject *Sender)
{
HANDLE pHandle = serverThread->getPipeHandle();
if(pHandle==NULL)
{
ShowMessage("句柄为NULL");
return;
}
wchar_t *str = Edit1->Text.t_str();
int i=0;
char buff[1024];
while(str[i]!='\0')
{
buff[i++]=(char)str[i];
}
buff[i]='\0';
ShowMessage(buff);
DWORD len;
bool hr = WriteFile(pHandle,buff,strlen(buff),&len,NULL);
if(hr)
{
ShowMessage("消息发送成功");
}
else
{
ShowMessage("消息发送失败");
}
}
客户端程序:
void __fastcall ClientThread::Execute()
{
wchar_t *pipeName = L"\\\\192.168.2.108\\pipe\\testpipe";
if(WaitNamedPipe(pipeName,NMPWAIT_WAIT_FOREVER)==FALSE)
{
ShowMessage(L"未找到服务器");
return;
}
ShowMessage("客户端成功连接服务器");
pipe_handle = CreateFile(pipeName,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_WRITE_THROUGH,
NULL);
if(pipe_handle!=INVALID_HANDLE_VALUE)
{
char buf[1024];
DWORD len;
Sleep(1500);
while(1)//消息的接收
{
Sleep(300);
if(ReadFile(pipe_handle,buf,1024,&len,NULL))//如果一直没有接收到消息则处于阻塞状态
{
buf[len]='\0';
Form1->Edit1->Text = buf;
}
}
}
}