首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

请问关于delphi命名管道的有关问题

2012-03-26 
请教关于delphi命名管道的问题下面是网上找的一个事例,但在本机报错.请教下错误原因,或者给另外的事例更好

请教关于delphi命名管道的问题
下面是网上找的一个事例,但在本机报错.

请教下错误原因,或者给另外的事例更好!谢谢
//Server
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;
type
  TServer = class(TForm)
  Button1: TButton;
  Memo1: TMemo;
  procedure Button1Click(Sender: TObject);
  private
  { Private declarations }
  public
  { Public declarations }
  end;

var
  Server: TServer;
const
 pipename:string='\\.\pipe\Server';
implementation

{$R *.dfm}

procedure TServer.Button1Click(Sender: TObject);

  var
  SPipeHandle:THandle;  
  Se:TSecurityAttributes;
  WriteBuffer:DWORD;  
  Buffer:pchar;
  begin
  Se.nLength:=Sizeof(TSecurityAttributes);
  Se.lpSecurityDescriptor:=nil;
  Se.bInheritHandle:=True;
  SPipeHandle:=CreateNamedPipe(pchar(pipename),PIPE_ACCESS_OUTBOUND OR FILE_FLAG_WRITE_THROUGH, PIPE_TYPE_BYTE or PIPE_WAIT,2,512,0,1000,@Se);

//此处建立并放回句柄
  if SPipeHandle=-1 then
  raise Exception.Create('Create pipe Failed');
  try
  if not ConnectNamedPipe(SPipeHandle,nil) then//此处会判断连接出错 begin
  CloseHandle(SPipeHandle);
  Raise Exception.Create(IntToStr(GetLastError)+'fail con');
  end;
  Buffer:=StrAlloc(512);
  Buffer:=Pchar(Memo1.Text);
  WriteFile(SPipeHandle,Buffer,512,WriteBuffer,nil);
  finally
  DisConnectNamedPipe(SPipeHandle);
  CloseHandle(SPipeHandle);
  end;
  end;



end.
//client
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type
  TClient = class(TForm)
  Memo1: TMemo;
  Timer1: TTimer;
  procedure Timer1Timer(Sender: TObject);
  private
  { Private declarations }
  public
  { Public declarations }

  end;

var
  Client: TClient;
  Buffer:array[0..511] of char;
  ReadSize:DWORD;
  hh:Thandle;
const  
  PipeName:string='\\.\pipe\Server';
implementation

{$R *.dfm}
procedure TClient.Timer1Timer(Sender: TObject);
begin
  if WaitNamedPipe(pchar(PipeName),NMPWAIT_USE_DEFAULT_WAIT) then
  begin // raise Exception.Create('failed wait');
  hh:=CreateFile(pchar(pipename),GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE,NiL,OPEN_EXISTING,FILE_ATTRIBUTE_ARCHIVE or FILE_FLAG_WRITE_THROUGH,0);
  if hh=INVALID_HANDLE_VALUE then
  showmessage('error createfile')
  else
  begin  
  readsize:=0;
  fillchar(buffer,512,0);
  readfile(hh,buffer,512,readsize,nil);  
  if readsize >0 then
  Memo1.Text:=Buffer;
  end;
  end;
end;

end.


[解决办法]
如管道已连接,就返回Ture(非零);如发生错误,或者管道已经连接,就返回零(GetLastError此时会返回ERROR_PIPE_CONNECTED)

热点排行