I need to send a set of bit fields along with a string of characters from a client to a server.
So given I have:
#define YES 1
#define FLAG 2
int main(int argc, char* argv[])
{
return sendToServer("The Message", YES | FLAG);
}
int sendToServer(char* msg, int bitfields)
{
/* create socket and connect to server */
/* Assume sock is set */
send(sock, msg, strlen(msg), 0);
return 0;
}
What would be the best way to send the bitfields? Is there anyway to send the bitfields along with the string?
EDIT: Ok I’m trying to implement Vlad’s method. My client is pretty much identical to what he wrote. I have put the flag at the beginning data[0] and I used htonl instead of bswap. My server:
int main(int argc, char* argv[])
{
/* create socket and wait for connection */
char buffer[BUFFERSIZE];
size_t rcvdB = recv(clntSock, buffer, sizeof(int),0);
int flags = ntohl((int) buffer);
rcvdB = recv(clntSock, buffer, sizeof(size_t),0);
size_t msgSize = ntohl((size_t) buffer);
rcvdB = recv(clntSock,buffer,msgSize,0);
/* Then I send back to the client */
ssize_t sntB = send(clntSock,buffer,msgSize,0);
}
When the client prints the message there are multiple ascii characters at the end of the message.
EDIT2:
The issue seems to occur when I read more than 8 bytes of data
As others have pointed out, it depends on a protocol. I’d use something like this:
On the receiving side, you can read the first
sizeof (size_t)bytes, convert from network to host byte order, cast tosize_t. That will tell you length of string. Then read buffer of that length – that will be your string. Finally, read anothersizeof (int)bytes – that will be your bitfield.See also: