How can I send std :: vector <std :: string> via a UNIX socket?
For my application, I need to send std::vector<std::string>via a UNIX socket (local) and get a copy of the vector on the other end of the socket. The easiest way to do this using messages O(1)regarding the size of the vector (i.e., without sending a message for each line in the vector)?
Since this is all on the same host, and since I control both ends of the socket, I am not interested in machine-related problems like endinness or vector / string.
I would like to avoid using any external libraries for various reasons.
std::string . , nul- API-, . , , , .
...
long length = htonl( vec.size() );
write( socket, &length, sizeof(length) );
for ( int i = 0; i < vec.size(); ++i ) {
length = htonl( vec[i].length() );
write( socket, &length, sizeof(length) );
write( socket, vec[i].data(), vec[i].length() );
}
...
:
...
std::vector vectorRead;
long size = 0;
read( socket, &size, sizeof( size ) );
size = ntohl( size );
for ( int i = 0; i < size; ++i ) {
std::string stringRead;
long length = 0;
read( socket, &length, sizeof( length ) );
length = ntohl( length );
while ( 0 < length ) {
char buffer[1024];
int cread;
cread = read( socket, buffer, min( sizeof( buffer ), length ) );
stringRead.append( buffer, cread );
length -= cread;
}
vectorRead.push_back( stringRead );
}
...
, ( , ). :
- . <, string > .
- dtors . memcpy ( ), .
, : memcpy'd.
- . , ICE, http://www.zeroc.com/
- - , , memcpy'd
- , . . recv reinterpret_cast recv .
2 , . .
3 vritually , recv. ForwardIterators, : , , , int .
reinterpret_cast'd , . O (1) .
O (1) , 2. , , X Y . , , . , , , . , , , - recv, .
You might want to take a look at the interprocess acceleration for more ideas on how to create containers that can be popped through sockets without serialization.