In Delphi, you can use named pipes to communicate between processes on the same computer or between processes on different computers across a network.
To create a named pipe in Delphi, you can use the CreateNamedPipe function from the Windows API. Here is an example of how to use this function to create a named pipe:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | const   PIPE_ACCESS_DUPLEX = $00000003;   PIPE_TYPE_MESSAGE = $00000004;   PIPE_READMODE_MESSAGE = $00000002;   PIPE_WAIT = $00000000;   PIPE_UNLIMITED_INSTANCES = 255; var   PipeHandle: THandle;   PipeName: string; begin   PipeName := ‘\\.\pipe\MyPipe’;   PipeHandle := CreateNamedPipe(PChar(PipeName),     PIPE_ACCESS_DUPLEX,     PIPE_TYPE_MESSAGE or PIPE_READMODE_MESSAGE,     PIPE_UNLIMITED_INSTANCES,     1024, 1024,     0,     nil);   if PipeHandle = INVALID_HANDLE_VALUE then   begin     // handle error   end;   // use PipeHandle to read from and write to the pipe end; | 
This code creates a named pipe with the name \\.\pipe\MyPipe and assigns the handle to the variable PipeHandle. The pipe is created with full duplex access, meaning that it can be used for both reading and writing. It is also created as a message pipe, meaning that data is written and read as discrete messages rather than as a continuous stream.
To read from or write to the named pipe, you can use the ReadFile and WriteFile functions from the Windows API. Here is an example of how to use these functions to write a message to the pipe and then read a response from the pipe:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var   BytesWritten, BytesRead: DWORD;   Buffer: array[0..1024] of Char;   Message: string; begin   Message := ‘Hello, world!’;   if WriteFile(PipeHandle, Message[1], Length(Message), BytesWritten, nil) then   begin     if ReadFile(PipeHandle, Buffer, 1024, BytesRead, nil) then     begin       SetString(Message, Buffer, BytesRead);       // do something with the message received from the pipe     end;   end; end; | 
This code writes the message 'Hello, world!' to the pipe and then reads a response from the pipe into the Buffer array. The BytesRead variable is used to store the number of bytes that were read from the pipe. The response message is then stored in the Message string.
Leave a Reply