I have server and client to send/receive a string through windows sockets.
Client code (sender):
string c = "Haha";
sprintf(temp.Buffer, c.c_str());
temp.len = c.size();
int sent = 0;
if ((sent = sendto(s, temp.Buffer, temp.len + 1, 0, (SOCKADDR*)&sa_in, sizeof(sa_in))) == SOCKET_ERROR) {
cout << "Send request method failed\n";
}
Server code (receiver):
if (!(outfds = select (1 , &readfds, NULL, NULL, NULL))) {//timed out
cout << "timed out";
}
if (outfds == 1)
{
fromlen = sizeof sa_in;
received = recvfrom(s, buf, 2048, 0, (struct sockaddr*)&sa_in, &fromlen);
}
In the server, I’ve noticed if the string I send from the client is smaller than a number of bytes (like 0-8~) the ‘buf’ variable contains garbage at the end of it. For example, I’ll send the string “ahah” and the server will receive a string similar to “ahah0`”. If I send “Hello World”, it receives it correctly. The char buffers in the client and server are both of size 2048.
A solution I found to this was to add +1 to the length in the sendto() method. I don’t want this to bite me in the a** later if I send something bigger than the maximum allowed size.
Does anyone know where this is coming from and do you have a better solution?
Edit: The number of bytes sent and received is always the same.
Thanks
You are not transmitting the trailing
'\0'char. Does your protocol specify a nul-terminated string? If so, change your client thus:If your protocol specifies that you do not send the nul termination, then modify your server thus:
If your protocol does not specify, then stop coding now and finish writing your protocol spec.