服务器端:
procedure Tform1.sendonnet(s1:string);
var
ASlotName:string;
FHandle:integer;
A: array[0..9] of Char;
begin
ASlotName := '//' + 'domain' + '/mailslot/' + 'client'; // 开启 MailSlot(档案)
FHandle := CreateFile(pchar(ASlotName),
GENERIC_WRITE, // Client 端对於 MailSlot 只能写入
FILE_SHARE_READ, // 设定为可供分享读取
Nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if FHandle = INVALID_HANDLE_VALUE then Exit;
StrPCopy(A, S1);
FileWrite(Fhandle, A, Length(s1));
end;
客户端:
function TForm1.ReadFromMailSlot:string;
var
NextSize: DWORD;
MessageCount: DWORD;
Result0: BOOL;
Buffer: pchar;
begin
if FHandle = INVALID_HANDLE_VALUE then Exit;
// 侦测 MailSlot 中是否有资料
Result0 := GetMailslotInfo(Fhandle, nil,
NextSize, @MessageCount, nil);
if not Result0 or (NextSize = MAILSLOT_NO_MESSAGE) then
Exit;
// 如果还有资料 (MessageCount <> 0),逐一读出资料
while Result0 and (MessageCount <> 0) do
begin
// 资料的长度
Buffer := AllocMem(NextSize + 1);
try
// 读出资料
FileRead(Fhandle, Buffer^, NextSize);
result:=StrPas(Buffer);
finally
FreeMem(Buffer, NextSize + 1);
end;
// 继续看看 MailSlot 中还有没有资料
Result0 := GetMailslotInfo(Fhandle, nil, NextSize, @MessageCount, nil);
end;
end;