PDA

View Full Version : Sending structure throurh TCP socket



veeresh
4th June 2013, 14:16
I am using TCP socket to send the below structure data from one application to another application

Struct message
{

std::string messagedata;
std::string date;
std::string time;
std::string source;
std::string filepath;
}

sending side i have used below code to send the structure data

message *l_msgInfo = new message;
char *p = (char*)l_msgInfo; // cast it to char* to make a QByteArray
QByteArray packet(p, sizeof(message));


at receiver side i have used below code

message *l_info = new messageinfo;
QByteArray l_ba;
message *l_info = new message;
l_inFromClient >> l_ba; l_info = (message*)l_ba.constData();


problem facing:
sender side, if string size is less than 16 bytes(example: error_messages1) than receiver side i am getting that string, otherwise i am receiving Bad_pointer error.

example1:
sender side:
message.messagedata = "error_messages1" //less that 16bytes
message.date= "04-06-2013" //less that 16bytes
message.time= "17::05::02" //less that 16bytes
message.source= "error_messages2" //less that 16bytes
message.filepath= "C:\temp" //less that 16bytes

receiver side i am getting the complete structure

example2:
sender side:
message.messagedata = "error_messages123" //greaterthan 16bytes
message.date= "04-06-2013" //greaterthan 16bytes
message.time= "17::05::02" //less that 16bytes
message.source= "error_messages2" //less that 16bytes
message.filepath= "C:\temp\test\filter\file" //greaterthan 16bytes

at receiver side am get

message.messagedata = "Bad Ptr"
message.date= "04-06-2013"
message.time= "17::05::02"
message.source= "error_messages2"
message.filepath= "Bad Ptr"

please help me out to how to resolve this problem?
Thanks in advance,
Veeresh.

Santosh Reddy
4th June 2013, 15:12
You cannot send that structure that way, when it contains datatype which are not binary copyable.

Here is just one example:
You can convert all the structure data in to char data and then send it


struct message
{
std::string messagedata;
std::string date;
std::string time;
std::string source;
std::string filepath;
}

message msg;
std::string str = msg.messagedata + "," + msg.date + "," + msg.time + "," + msg.source + "," + msg.filepath;

QByteArray bytes(str.c_str(), str.length());

//send bytes

//reveive bytes.
// split it into sub-string
// store is back into struct.