//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "SockAddServer.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm3 *Form3;

#define DEFAULT_PORT 2501
//---------------------------------------------------------------------------
// BeginExample: TTcpServer
// Class: Sockets.TTcpServer
// Method: Sockets.TBaseSocket.ReceiveBuf
// Event: Sockets.TCustomTcpServer.OnAccept
// Event: Sockets.TBaseSocket.OnCreateHandle
// Event: Sockets.TBaseSocket.OnDestroyHandle
// Property: Sockets.TIpSocket.LocalPort

// BeginCode
/*
This example demonstrated the use of TTcpServer in order to receive
a buffer (stream) and process it. It is to be used with the example
from TTcpClient section.
This example uses three buttons, one for activating the server, one
for deactivating it and the third for clearing the Memo.
*/
__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;

}
//---------------------------------------------------------------------------
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 width " +
						IntToStr(a[9]));
	for (int i=0; i < 9; i++)
	{
		Memo1->Lines->Add(IntToStr(a[i] + a[9]));
	}
	Memo1->Lines->Add("--------------------");

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

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

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

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