What is a good way of sending data as strings through sockets?
As there several ways to exchange data in the form of strings over sockets, such as:
using functions like:
sprintf()
andsscanf()
snprintf()
andsscanf()
printf()
andstrtof()
or converti开发者_运维百科ng to char and then passing it as an array
I would appreciate if you could suggest which way and why it is efficient and better than others, or if there is another way not mentioned above. At the moment I am using the simplest way, I mean sprintf()
and sscanf()
functions. But I read on the web that e.g. using snprintf()
function is more safe.
if you just want to send strings, you can get away with something like this; it's serialization in a simple form: a header containing the size of the data following.. (pseudo-code)
Send( socket, const string& str )
{
const size_t len = str.length();
send( socket, &len, sizeof( len ) );
send( socket, str.data(), len );
}
Receive( socket, string& str )
{
size_t len;
receive( socket, &len, sizeof( len ) );
str.resize( len );
receive( socket, str.data(), len );
}
Edit: see comment 1, a faster Send method would be
Send( socket, const string& str, rawmemory& packet )
{
const size_t len = str.length();
packet.Reserve( len + sizeof( len ) );
packet.ResetOffset();
packet.CopyFrom( &len, sizeof( len ) );
packet.CopyFrom( str.data(), len );
send( socket, packet.Data(), packet.Length() );
}
in C++ you can also use StringStream
stringstream ss;
int i = 1;
float f = "1.0";
char separtor = ';';
ss << i << separtor << f;
you can then extract the string with ss.str().c_str()
ss.str().c_str()
will result in the case above with
"
1;1.0
"
Have a look at Serialization—How to Pack Data.
It's easy enough to send text data across the network, you're finding, but what happens if you want to send some "binary" data like ints or floats? It turns out you have a few options.
- Convert the number into text with a function like sprintf(), then send the text. The receiver will parse the text back into a number using a function like strtol().
- Just send the data raw, passing a pointer to the data to send().
- Encode the number into a portable binary form. The receiver will decode it.
精彩评论