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

#include <vcl.h>
#pragma hdrstop

#include "frmClientSocket.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ConnectClick(TObject *Sender)
{
	if (!_clientSocket->Active) {
		_clientSocket->Host = this->_serverIP->Text;
		_clientSocket->Port = this->_serverPort->Text.ToInt();
		_clientSocket->Open();
	}
	this->_disconn->Enabled = true;
	this->Connect->Enabled = false;
	this->_Send->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::_disconnClick(TObject *Sender)
{
	if (_clientSocket->Active) {
		_clientSocket->Close();
	}
	this->Connect->Enabled = true;
	this->_disconn->Enabled = false;
	this->_Send->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::_SendClick(TObject *Sender)
{
	int hexBufLen = _sendBuf->Text.Length()/2;
	char *buf = 0;

	if (this->CheckBox1->Checked) {
		buf = new char[hexBufLen];
		HexToBin(_sendBuf->Text.c_str(),buf,hexBufLen);
		_clientSocket->Socket->SendBuf(buf,hexBufLen);
		delete [] buf;
	}
	else {
		_clientSocket->Socket->SendBuf(_sendBuf->Text.c_str(),_sendBuf->Text.Length()*sizeof(wchar_t));
  }


}
//---------------------------------------------------------------------------
void __fastcall TForm1::_clientSocketRead(TObject *Sender, TCustomWinSocket *Socket)

{
	UnicodeString us;
	int len = Socket->ReceiveLength();
	//int hexLen = len *2;
	char *buf = new char[len];
	char *hexBuf = new char[len*2];
	Socket->ReceiveBuf(buf,len);
	us = UnicodeString((wchar_t*)buf,len/2);
	this->_stringMemo->Lines->Add(us);
	BinToHex(buf, hexBuf, len);  // len is for buf
	this->_hexMemo->Lines->Add(UnicodeString(hexBuf,len*2));
	delete [] buf;
	delete [] hexBuf;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::_clientSocketError(TObject *Sender, TCustomWinSocket *Socket,
          TErrorEvent ErrorEvent, int &ErrorCode)
{
	ErrorCode = 0;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
	this->_stringMemo->Lines->Clear();
	this->_hexMemo->Lines->Clear();
}
//---------------------------------------------------------------------------

