TTcpClientSendStream (C++)
Description
This example demonstrates the use of the SendStream method and can be used with the example for TTcpServer_(C++).
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 and include <memory>.
#define DEFAULT_PORT 2501//The default port for the communication
#include <memory> //For the STL auto_ptr class
Add the code below to the OnClick event of the button:
void __fastcall TForm2::Button1Click(TObject *Sender)
{
//Creating a stream
// TMemoryStream* myStream = new TMemoryStream();
std::auto_ptr<TMemoryStream> myStream(new TMemoryStream);
for (byte i = 0; i < 9; i++)
{
myStream->WriteBuffer(&i,1);
}
int 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.get());
TcpClient1->Active = false;
//Free the stream.
// delete myStream;
}
Add the code below to the OnCreate event handler of the form.
void __fastcall TForm2::FormCreate(TObject *Sender)
{
Edit1->Text = "0";
Memo1->Lines->Clear();
TcpClient1 = new TTcpClient(this);
//TcpClient1->OnSend = TcpClient1Send;
TcpClient1->RemotePort = DEFAULT_PORT;
TcpClient1->RemoteHost = "localhost";
}
Add the code below to the OnSend event handler of the TTcpClient.
void __fastcall TForm2::TcpClient1Send(TObject *Sender, PChar Buf, int &DataLen)
{
TDateTime now = TDateTime::CurrentDateTime();
Memo1->Lines->Add(DateTimeToStr(now) + " Send data with " + Edit1->Text);
}
Add the code below to the OnCreateHandle event handler of the TTcpClient.
void __fastcall TForm2::TcpClient1CreateHandle(TObject *Sender)
{
// This procedure displays on the memo when the client is ready to send the message or the message was sent to the server
TDateTime now = TDateTime::CurrentDateTime();
if (Memo1->Text!= "") {
Memo1->Lines->Add(DateTimeToStr(now)+ "sending...");
}
else
{
Memo1->Lines->Add(DateTimeToStr(now)+ "ready");
}
}
Add the code below to the OnDestroyHandle event handler of the TTcpClient.
void __fastcall TForm2::TcpClient1DestroyHandle(TObject *Sender)
{
//This procedure displays on the memo when the message was send
TDateTime now = TDateTime::CurrentDateTime();
if (this->Memo1 != NULL)
Memo1->Lines->Add(DateTimeToStr(now) + " sent");
Edit1->Text=" ";
}
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 )