TTcpClientSendStream (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the SendStream method. It can be used with the example for TTcpServer_(Delphi).

To build this example, create a VCL Forms Application. Add a button, a memo box, an edit box, and a TTcpClient from the Tool Palette.

Code

Define the default port for the communication.

const DEFAULT_PORT = 2501;//The default port for the communication

Add the code below to the OnClick event of the button:

procedure TForm3.Button1Click(Sender: TObject);
var
  myStream : TMemoryStream;
  I : Cardinal;
  userValue : Integer;
begin
  //Creating a stream
  myStream := TMemoryStream.Create();
  for I := 0 to 8 do
  begin
    myStream.WriteBuffer(I,1);
  end;
  userValue := StrToIntDef(Edit1.Text, 0);
  myStream.WriteBuffer(userValue,1);

  //Resetting the stream position
  myStream.Seek(0,0);

  //Sending the stream
  TcpClient1.Active := true;
  TcpClient1.SendStream(myStream);
  TcpClient1.Active := false;

  //Free the stream
  myStream.Free;

end;

Add the code below to the OnCreate event handler of the form.

procedure TForm3.FormCreate(Sender: TObject);
begin
  Edit1.Text := '0';
  Memo1.Lines.Clear;

  TcpClient1.RemotePort := IntToStr(DEFAULT_PORT);
  TcpClient1.RemoteHost := 'localhost';
  TcpClient1.Active := true;
end;

Add the code below to the OnSend event handler of the TTcpClient.

procedure TForm3.TcpClient1Send(Sender: TObject; Buf: PWideChar;
  var DataLen: Integer);
begin
  Memo1.Lines.Add(DateTimeToStr(now) + ' Send data with ' + Edit1.Text);
end;

Add the code below to the OnCreateHandle event handler of the TTcpClient.

procedure TForm2.TcpClient1CreateHandle(Sender: TObject);
begin
// This procedure displays on the memo whether the client is ready to send the message or the message was sent to the server
   if Memo1.Text<> ''
   then
   begin
      Memo1.Lines.Add(DateTimeToStr(now) + ' sending...');
   end
   else
   begin
      Memo1.Lines.Add(DateTimeToStr(now) + ' ready');
   end;
end;

Add the code below to the OnDestroyHandle event handler of the TTcpClient.

procedure TForm2.TcpClient1DestroyHandle(Sender: TObject);
begin
//This procedure displays on the memo when the message was sent
  if Self.Memo1 <> nil then
    Memo1.Lines.Add(DateTimeToStr(now) + ' sent');
  edit1.text:=' ';
end;

Uses

  • Web.Win.Sockets.TTcpClient ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.SendStream ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.OnSend ( fr | de | ja )
  • Web.Win.Sockets.TIpSocket.RemoteHost ( fr | de | ja )
  • Web.Win.Sockets.TIpSocket.RemotePort ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.Active ( fr | de | ja )
  • Web.Win.Sockets.TTcpClient.OnCreateHandle ( fr | de | ja )
  • Web.Win.Sockets.TTcpClient.OnDestroyHandle ( fr | de | ja )