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.

+3
source share
6 answers

, , <string1>\0<string2>\0...<stringN>\0 ( ). , , std::string , , .

+1

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 );
}
...
+11

.

, : STL.

- . , , ( NULL) , .

+2

, ++, writev(2) (aka / -). .

+1

, . socket api char . ( , api-, - ). , - stl. , , , , ( , ) . , , . , , stl. ( * NIX, * POSIX-), CHAR , , , . char, DESIGNED, ,

, , , STL , . , , 0 , ,   & myvector [0]

... "", . , , size_t ,  myvector.size()

,

+1

, ( , ). :

  • . <, string > .
  • dtors . memcpy ( ), .

, : memcpy'd.

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.

0
source

Source: https://habr.com/ru/post/1741551/


All Articles