To create a TCP server-client communication in Delphi FMX, you can use the TIdTCPServer and TIdTCPClient components from the IdTCPServer and IdTCPClient units.
Here is an example of how you can use these components to create a simple TCP server and client in Delphi FMX;
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
uses IdTCPServer, IdTCPClient; procedure TForm1.FormCreate(Sender TObject); var TCPServer TIdTCPServer; TCPClient TIdTCPClient; begin //Create the TCP server TCPServer = TIdTCPServer.Create(Self); TCPServer.DefaultPort = 12345; TCPServer.OnExecute = TCPServerExecute; TCPServer.Active = True; //Create the TCP client TCPClient = TIdTCPClient.Create(Self); TCPClient.Host = ‘127.0.0.1’; Set the host to the local loopback address TCPClient.Port = 12345; end; procedure TForm1.TCPServerExecute(AContext TIdContext); var Request string; begin Request = AContext.Connection.IOHandler.ReadLn; Memo1.Lines.Add(Request); AContext.Connection.IOHandler.WriteLn(‘OK’); end; procedure TForm1.Button1Click(Sender TObject); var TCPClient TIdTCPClient; Response string; begin TCPClient = TIdTCPClient.Create(Self); try TCPClient.Host = ‘127.0.0.1’; Set the host to the local loopback address TCPClient.Port = 12345; TCPClient.Connect; TCPClient.IOHandler.WriteLn(Edit1.Text); Response = TCPClient.IOHandler.ReadLn; Memo1.Lines.Add(Response); finally TCPClient.Disconnect; TCPClient.Free; end; end; |
In this example, the TCP server listens on port 12345 and prints received data to a TMemo component. The client sends data to the server and receives a response when the user clicks a button.
Leave a Reply