TTcpServer (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of TTcpServer to receive a buffer (in this case, a stream) and to process it. The example can be used with the example for TTcpClientSendStream_(C++). To build this example, create a VCL Forms Application. Add three buttons (Connect, Disconnect, Clear), a memo box, and a TTcpServer from the Tool Palette.

Code

Define the default port for the communication.

#define DEFAULT_PORT 2501//The default port for the communication

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

__fastcall TForm3::TForm3(TComponent* Owner)
	: TForm(Owner)
{
	Memo1->Lines->Clear();

	//Server initialization
	TcpServer1 = new TTcpServer(this);
	TcpServer1->OnAccept = TcpServer1Accept;
	TcpServer1->OnCreateHandle = TcpServer1CreateHandle;
	TcpServer1->OnDestroyHandle = TcpServer1DestroyHandle;

}

Add the code below to the OnAccept event handler of the TTcpServer.

void __fastcall TForm3::TcpServer1Accept(TObject *Sender, TCustomIpClient *ClientSocket)
{
	byte a[10];
	ClientSocket->ReceiveBuf(a,10,0);
	TDateTime now = TDateTime::CurrentDateTime();
	Memo1->Lines->Add(DateTimeToStr(now) + " Data added with " +
						IntToStr(a[9]));
	for (int i=0; i < 9; i++)
	{
		Memo1->Lines->Add(IntToStr(a[i] + a[9]));
	}
	Memo1->Lines->Add("--------------------");

}

Add the code below to the OnClick event of the 'Connect' button.

void __fastcall TForm3::Button1Click(TObject *Sender)
{
	TcpServer1->LocalPort = DEFAULT_PORT;
	TcpServer1->Active = true;
}

Add the code below to the OnClick event of the 'Disconnect' button.

void __fastcall TForm3::Button2Click(TObject *Sender)
{
	TcpServer1->Active = false;
}

Add the code below to the OnClick event of the 'Clear' button.

void __fastcall TForm3::Button3Click(TObject *Sender)
{
	Memo1->Lines->Clear();
}

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

void __fastcall TForm3::TcpServer1CreateHandle(TObject *Sender)
{
	TDateTime now = TDateTime::CurrentDateTime();
	Memo1->Lines->Add(DateTimeToStr(now) + " Server started ");
}

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

void __fastcall TForm3::TcpServer1DestroyHandle(TObject *Sender)
{
	TDateTime now = TDateTime::CurrentDateTime();
	if(this->Memo1)
	{
		Memo1->Lines->Add(DateTimeToStr(now) + " Server stopped ");
    }
}

Uses

  • Web.Win.Sockets.TTcpServer ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.ReceiveBuf ( fr | de | ja )
  • Web.Win.Sockets.TCustomTcpServer.OnAccept ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.OnCreateHandle ( fr | de | ja )
  • Web.Win.Sockets.TBaseSocket.OnDestroyHandle ( fr | de | ja )
  • Web.Win.Sockets.TIpSocket.LocalPort ( fr | de | ja )