unit MainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
System.Net.Socket;
type
TForm1 =
class(TForm)
ButtonSend: TButton;
MemoLog: TMemo;
procedure ButtonSendClick(Sender: TObject);
private
FSocket: TSocket;
procedure AsyncCallback(
const ASyncResult: IAsyncResult);
procedure DisplayReceivedData(
const AData: TBytes);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.ButtonSendClick(Sender: TObject);
var
DataToSend: TBytes;
begin
DataToSend := TEncoding.UTF8.GetBytes('
Hello, server!');
if not Assigned(FSocket)
then
begin
FSocket := TSocket.Create(TIPAddress.Any, 0);
FSocket.Connect('
127.0.0.1', 1234);
FSocket.BeginSend(DataToSend, 0, Length(DataToSend), AsyncCallback,
nil);
end;
end;
procedure TForm1.AsyncCallback(
const ASyncResult: IAsyncResult);
var
BytesReceived: Integer;
ReceivedData: TBytes;
begin
try
BytesReceived := FSocket.EndReceive(ASyncResult);
if BytesReceived > 0
then
begin
SetLength(ReceivedData, BytesReceived);
FSocket.ReceiveBuffer.
Read(ReceivedData, 0, BytesReceived);
TThread.Queue(
nil,
procedure
begin
DisplayReceivedData(ReceivedData);
end);
end;
except
on E:
Exception do
begin
TThread.Queue(
nil,
procedure
begin
MemoLog.Lines.Add('
Error: ' + E.
Message);
end);
end;
end;
end;
procedure TForm1.DisplayReceivedData(
const AData: TBytes);
begin
MemoLog.Lines.Add('
Received: ' + TEncoding.UTF8.GetString(AData));
end;
end.