I'm sending messages over TCP/IP, I need to prefix message length in a char array and then send it. How do I do it?
Also can you please provide an example of how to extract it at the another end. And if possible, please explain.
I'm using C++ and Winsock.
EDIT:
string writeBuffer = "Hello";
unsigned __int32 length = htonl(writeBuffer.length());
It's not returning the correct length rather a very large number.
For the receiving part, if I use ntohl(), then I also get a large number instead of the correct length? Why is that so? I'm receiving like this
bool Server::Receive(unsigned int socketIndex)
{
// Read data from the socket
if (receivingLength)
{
bytesReceived = recv(socketArray[socketIndex - WSA_WAIT_EVENT_0],
((char*)&messageLength) + bytesReceived, MESSAGE_LENGTH_SIZE - bytesReceived, 0);
if (bytesReceived == SOCKET_ERROR)
{
return false;
}
if (bytesReceived == MESSAGE_LENGTH_SIZE)
{
// If uncomment the following line,
// I won't get the correct length, but a large number
//messageLength = ntohl(messageLength);
receivingLength = false;
bytesReceived = 0;
bytesLeft = messageLength;
}
}
else
{
if (bytesLeft > BUFFER_SIZE)
{
return false;
}
bytesReceived = recv(socketArray[socketIndex - WSA_WAIT_EVENT_0],
&receiveBuffer[bytesReceived], bytesLeft, 0);
if (bytesReceived == SOCKET_ERROR)
{
return false;
}
if (bytesReceived == messageLength)
{
// we have received full message
messageReceived = true;
receiveBuffer[bytesReceived] = '\0';
// wait for next message
receivingLength = true;
}
bytesLeft -= bytesReceived;
}
return true;
}