- Code: Select all
void __fastcall TForm1::Edit1KeyDown(TObject *Sender, Char &Key, TShiftState Shift)
{
if(Key == VK_ESCAPE)
{
Close();
return;
}
if(Key == VK_RETURN)
{
if(!Client->Socket->Connected)
{
Edit1->Clear();
Beep();
return;
}
if( Edit1->GetTextLen() < 1)
{
return;
}
// in BCB2009, this will convert the Text from
// Unicode to Ansi, which the server code is
// expecting anyway (better would be to use
// UTF-8 on both ends instead so there is no
// data loss).
//
// In earlier versions, this will send the
// TEdit::Text data as-is.
//
AnsiString s = Edit1->Text;
Client->Socket->SendBuf(s.c_str(), s.Length());
Memo1->Lines->Add("I'm saying:");
Memo1->Lines->Add(s);
}
}
Also, his TClientSocket::OnRead() event handler has a minor buffer overflow bug in it:
- Code: Select all
void __fastcall TForm1::ClientRead(TObject *Sender, TCustomWinSocket *Socket)
{
int length = Socket->ReceiveLength();
if( length < 1 )
{
return;
}
char *pszBuffer = new char[length];
try
{
Socket->ReceiveBuf(pszBuffer, length);
// the data is NOT null-terminated!
//
// AnsiString S = pszBuffer;
AnsiString S(pszBuffer, length);
Memo1->Lines->Add(S);
__finally
{
delete [] pszBuffer;
}
}
Something else to keep in mind is that SendText() and SendBuf() are NOT guaranteed to send everything they are given. In the case of SendBuf(), it returns the actual number of bytes written. The caller needs to look at that value and re-call SendBuf() again for any bytes that were not sent the previous time. But I'll leave that as an exercise for the readers to figure out
