命名管道实践(2)

电脑杂谈  发布时间:2020-07-25 18:01:42  来源:网络整理

其中,hlThread定义为

HANDLE hlThread;

在项目中引用AsyncPipe并定义管道对象

private NamedPipeStreamClient pipeClient = new NamedPipeStreamClient("TestC");

发送消息

pipeClient.SendMessage(Encoding.Default.GetBytes(tbSend.Text));

接收消息

双拥模范城(县)创建命名_成都哪儿有卖自来水管道堵漏器,管道修补器_创建命名管道

1. 定义委托

pipeClient.MessageReceived += new MessageEventHandler(pipeClient_MessageReceived);

2. 定义回调函数

void pipeClient_MessageReceived(object sender, MessageEventArgs args)
{
    string content = Encoding.Default.GetString(args.Message);
    this.tbReceive.Text += content;
}

定义管道对象

pipeNameStr:='\\.\Pipe\TestC';
if(WaitNamedPipe(pchar(pipeNameStr),NMPWAIT_WAIT_FOREVER)=FALSE) then
begin
   ShowMessage(format('WaitNamedPipe failed with error %d',[GetLastError()]));
   exit;
end;
pipeHandle := CreateFile(pchar(pipeNameStr),GENERIC_READ or GENERIC_WRITE,FILE_SHARE_WRITE,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED,0);
if pipeHandle = INVALID_HANDLE_VALUE then
begin
   ShowMessage(format('CreateFile failed with error %d',[GetLastError()]));
   exit;
end;

其中,pipeHandle和pipeNameStr被定义为

pipeHandle:HWND;
pipeNameStr:string;

发送消息

if WriteFile(pipeHandle,pchar(EditMessageToSend.Text)^,length(EditMessageToSend.Text),bytesWrite,nil)= False then
begin
   ShowMessage(format('WriteFile failed with error %d',[GetLastError()]));
   exit;
end;
ShowMessage(format('write %d Bytes',[bytesWrite]));

接收消息

  function ReadFromPipe(p:Pointer):DWORD;stdcall;
begin
  if pipeHandle <> INVALID_HANDLE_VALUE then
  begin
    while TRUE DO
    begin
      if ReadFile(pipeHandle,buffer,sizeof(buffer),bytesRead,nil)=FALSE then
      begin
        ShowMessage(format('ReadFile failed with error %d',[GetLastError()]));
        Application.Destroy;
      end;
      SendMessage(integer(p),WM_MYMSG,1,1);
    end;
  end ;
  result := 0;
end ;

其中,WM_MYMSG被定义为


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-288046-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    • 张甜甜
      张甜甜

      倒是身边守着世界最大的市场

    • 郭启航
      郭启航

      面对伊拉克要倒向请求帮助空袭

    热点图片
    拼命载入中...