I am trying to send a map composed of an int and another map over TCP socket in linux.
the map is of the form
map<int, map<string, double>>
Following this SO link i tried to do
unsigned char* mybytemap = reinterpret_cast<unsigned char*>(&my_map);
then to send the buffer i used write() function as follows:
int size = sizeof(mybytemap);
char temp[10];
sprintf(temp, "%d", size);
write(sockfd, temp, strlen(temp)); //send the size for the client
write(sockfd, mybytemap, sizeof(mybytemap));
On the client side:
char temp[10];
n = read(sockfd, temp, 10);
size = stoi(temp); //Got Size Of buffer
unsigned char * buf;
if(size != 0)
{
buf = new unsigned char[size];
int current=0;
while(current<size)
{
n = read(sockfd,(unsigned char*)(buf)+current, min(1024,size-current));
if (n <= 0)
{
cout<<"ERROR reading from socket when receiving"<<endl;
break;
}
current+=n;
}
}
map<int, map<string, double>> *test = reinterpret_cast< map<int, map<string, double>>* > (buf);
vector<int> ks;
for(map<int, map<string, double>>::iterator it = test->begin(); it != test->end(); ++it)
{
ks.push_back(it->first);
cout<<"id: "<<it->first<<endl;
}
but the Map isn't received correctly and code crashes when trying to access the data. how to fix that?
Do i need to XML the map? and if so can someone guide me on how to do that?