C++ Builder TtcpClient

2.9k views Asked by At
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    int size =  MemoEnter->GetTextLen() + 1;
    wchar_t *szBuff = new wchar_t[size];
    memset(szBuff, 0, sizeof(szBuff));
    MemoEnter->GetTextBuf((wchar_t *)szBuff, size);
    TcpClient->SendBuf(szBuff, sizeof(szBuff));
    LogOut->Lines->Add(szBuff);
    delete []szBuff;
}  

Why doesn't TcpClient send anything? Server is ok. connection is ok. Telnet sends data to the server but this code does not.

Guys! i tried to

TcpClient->SendBuf("fsd", 3);

and still got nothing

2

There are 2 answers

7
Remy Lebeau On

Your use of sizeof() is definately the problem. You are sending your data specifying the size of the pointer that points at the buffer, not the size of the buffer itself. The size of a pointer is 4 in 32-bit and 8 in 64-bit. You need to use the actual buffer size instead of the pointer size.

Rather than using the new[] operator, you should use the VCL's String class instead, eg:

void __fastcall TForm1::Button1Click(TObject *Sender) 
{ 
    String s = MemoEnter->Text; 
    TcpClient->SendBuf(s.c_str(), ByteLength(s)); 
    LogOut->Lines->Add(s); 
}

Note that String is an alias for UnicodeString. If the receiver is not expecting UTF-16 encoded data, then you need to convert the data to another encoding before you send it, eg:

void __fastcall TForm1::Button1Click(TObject *Sender) 
{ 
    String s = MemoEnter->Text; 
    UTF8String utf8 = s;
    TcpClient->SendBuf(utf8.c_str(), utf8.Length()); 
    LogOut->Lines->Add(s); 
}

Or:

void __fastcall TForm1::Button1Click(TObject *Sender) 
{ 
    String s = MemoEnter->Text; 
    AnsiString ansi = s; // <-- potential data loss for non-ASCII characters!
    TcpClient->SendBuf(ansi.c_str(), ansi.Length()); 
    LogOut->Lines->Add(s); 
}

Or:

void __fastcall TForm1::Button1Click(TObject *Sender) 
{ 
    String s = MemoEnter->Text; 
    AnsiStringT<SomeCodePage> ansi = s; // <-- use a suitable codepage to avoid data loss!
    TcpClient->SendBuf(ansi.c_str(), ansi.Length()); 
    LogOut->Lines->Add(s); 
}
2
hmjd On

This may be contributing to the problem:

sizeof(szBuff); // Returns the sizeof a wchar_t*,
                // not the number of characters in szBuff

Change:

memset(szBuff, 0, sizeof(szBuff));
...
TcpClient->SendBuf(szBuff, sizeof(szBuff));

To:

memset(szBuff, 0, sizeof(wchar_t) * size);
...
TcpClient->SendBuf(szBuff, wcslen(szBuff));

If the second argument of TcpClient->SendBuf() is the number of bytes, not characters, then change to:

TcpClient->SendBuf(szBuff, wcslen(szBuff) * sizeof(wchar_t));