Here's an example Delphi code that demonstrates how to create a named pipe server and client using the CreateNamedPipe and ConnectNamedPipe functions:
// Server code
var
hPipe: THandle;
lpvMessage: PChar;
cbBytesRead, cbWritten: DWORD;
begin
hPipe := CreateNamedPipe('\\.\pipe\MyPipe',
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE or PIPE_READMODE_MESSAGE or PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
0,
0,
0,
nil);
if hPipe = INVALID_HANDLE_VALUE then
begin
// Error handling
Exit;
end;
if not ConnectNamedPipe(hPipe, nil) then
begin
// Error handling
CloseHandle(hPipe);
Exit;
end;
GetMem(lpvMessage, BUFSIZE);
while True do
begin
if not ReadFile(hPipe, lpvMessage, BUFSIZE, @cbBytesRead, nil) then
begin
// Error handling
Break;
end;
// Process the message
if not WriteFile(hPipe, lpvMessage, cbBytesRead, @cbWritten, nil) then
begin
// Error handling
Break;
end;
end;
FreeMem(lpvMessage, BUFSIZE);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
end;
// Client code
var
hPipe: THandle;
lpvMessage: PChar;
cbWritten, cbRead: DWORD;
begin
hPipe := CreateFile('\\.\pipe\MyPipe',
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
0,
nil);
if hPipe = INVALID_HANDLE_VALUE then
begin
// Error handling
Exit;
end;
GetMem(lpvMessage, BUFSIZE);
// Prepare the message to be sent
StrPCopy(lpvMessage, 'Hello, world!');
if not WriteFile(hPipe, lpvMessage, BUFSIZE, @cbWritten, nil) then
begin
// Error handling
FreeMem(lpvMessage, BUFSIZE);
CloseHandle(hPipe);
Exit;
end;
if not ReadFile(hPipe, lpvMessage, BUFSIZE, @cbRead, nil) then
begin
// Error handling
FreeMem(lpvMessage, BUFSIZE);
CloseHandle(hPipe);
Exit;
end;
// Process the received message
FreeMem(lpvMessage, BUFSIZE);
CloseHandle(hPipe);
end;
In this example, the server creates a named pipe with the name \\.\pipe\MyPipe using the CreateNamedPipe function. The client then connects to this named pipe using the CreateFile function. The client then sends a message to the server using the WriteFile function, and the server reads this message using the ReadFile function. The server then sends a response message back to the client using the WriteFile function, and the client reads this message using the ReadFile function.