Full source code included: this project demonstrates how both sides in a client/server application can initiate request/response style communication. For the sake of simplicity, both the client and the server part are placed in the same VCL form application.
Client side

Server side

Implementation notes
For client and server, there is both a “Send request” button and a boolean flag, which is set in the button click event handler to indicate that the request message should be sent. Here is the main part in the client-side code, which runs in a thread:
while not Terminated do
begin
if Send then
begin
// send request to server and receive response
Send := False;
Request := 'REQ:' + FClientRequestHolder.Text;
TCPClient.IOHandler.WriteLn(Request);
repeat
Response := TCPClient.IOHandler.ReadLn(IndyTextEncoding_UTF8);
until Response <> '';
LogInMainThread(Request, Response);
end
else
begin
// receive request from server and send response
Request := TCPClient.IOHandler.ReadLn(IndyTextEncoding_UTF8);
if StartsStr('REQ:', Request) then
begin
Response := 'from client ' + ReverseString(Request);
TCPClient.IOHandler.WriteLn(Response);
end;
end;
end;
Background
A TCP socket is bidirectional and allows both sides to send and receive messages at any time. However, a message must identify what it is, a request or a response, so that they can be processed correctly, and no unsolicited events can disturb the communication. In the example, all requests have a prefix (‘REQ:’). Adding a prefix to the response is left as an exercise to the reader.
Discover more from Habarisoft Blog
Subscribe to get the latest posts sent to your email.