so I’m getting socket communication, AND I’m getting the proper message…however when I try to extract it from the receive buffer…it doesn’t work. My code looks something like this:
void CClientSocket::OnReceive(int nErrorCode)
{
char buff[1000];
int ibuf = Receive(buff,sizeof(buff));
buff[sizeof(buff)-1] ='\0';
CSocket::OnReceive(nErrorCode);
}
When I run in debug, the value of buff contains the proper message…along with a bunch of random characters filling up the unused portion of the array. However, I can’t use that data…if I try to convert to CString or even to transfer the characters to a different array…nothing works. I’m baffled and I really don’t know what to do.
Let me know if you need more info or if I am unclear in any way.
EDIT: some code I have tried to extract the data
CString string;
string = CString(buff);
AND
char *msg;
msg = new char[ibuf]
for(int i = 0; i < ibuf; i++){
msg[i] = (char)buff[i];
}
EDIT: some clarification
when i said ‘nothing works’ I meant that when I tried to convert it, the result was and empty CString or empty char etc…there are no errors.
Rather than that second line, put the zero byte at
buff[ibuf]. But before that, add an error check (make sureibuf > 0and if not, treat it as a connection drop.) Also, if you do it this way you shouldReceive(buff, sizeof(buff)-1);(note the-1– this accounts for the terminating character – thanks @Altnitak for pointing this out.)On the other hand… I would also argue that this is no way to treat socket code. Strings are not sent atomically over the network. They will be split. If you control the protocol, I suggest you depart the string-centered view of the universe, and structure your network communications so that messages begin with an integer (
uint16_toruint32_t, and make sure to callhtons/htonletc.) indicating the length of the payload that follows. Then keep buffering incoming bytes and process them when you have enough to satisfy the lengths specified.If you do not control the protocol, find a convenient marker that you can use to decide when to process content, and buffer bytes until you reach it. (For example if you’re doing HTTP, you might buffer chars until you see a newline while processing headers, then decide on a certain buffer size for the contents of the response…)