0
votes

I'm trying to send sensor data (double type) from client to server via TCP/IP (Winsock). In theory, after connected successfully, we will execute the command send().

I use 2 variables: stringstream ss and string res to store sensor data and convert double type into char type. But when I sent data, on the server showed: Date Time Current Voltage Air-Pressure 000000000000000000000000000000000000000… All data are 0.

I tried other methods but server only received empty or incorrect values. Please suggest me how to fix this problem. Here's my code:

char Data_Send[10000];
char item[] = " Date\t" "Time\t" "Current\t" "Voltage\t" "Air-Pressure\t";
string res;
stringstream ss;

strcpy(Data_Send, item);    
for (int32 i = 0; i < returnedCount; i = i + channelCount)
{
    ss << userDataBuffer[i];  // Sensor data
    ss >> res;
    strcat(Data_Send, (char*)&res);
}

if (connect(socketClient, (sockaddr*)&clientAddr, sizeof(clientAddr)) == 0)
                    {
                        cout << "\nConnection success..!";
                        cout << "\nConnect with Server's IP: " << inet_ntoa(clientAddr.sin_addr);
                        cout << "\nStart communicating";

                        cin.getline(Data_Send, 5120);
                        send(socketClient, (char*)&Data_Send, sizeof(Data_Send), 0);                
                    }
1
To get underlying data of string use c_str, not &res - it gets pointer of string instance not pointer to its buffer, so strcat(Data_Send, (char*)&res); should be strcat(Data_Send, res.c_str());rafix07
And use its length, not its sizeof, when sending. And error-check your send() call.user207421
@rafix07: I tried as your suggestion, but it still showed the same result as I did before.Hector Ta
Why are you calling cin.getline(Data_Send, 5120); before send? getline will overwrite entered data in Data_Send. Try sending without getline. Also send(socketClient, (char*)Data_Send, strlen(Data_Send), 0); rafix07
Before asking you, I also deleted that getline but result is the same. Actually, the program in server side is written in Labview by my colleague. So I'm not sure whether the problem is caused by his program. But he can still get correct result by his Labview client.Hector Ta

1 Answers

0
votes

I strongly suggest you to not send floating point data over a network. Instead of this send a integer representation of this values.

But if you really want to do it, the better way is to send the binary representation of the data in a know format (for example IEEE 754).

You can do it, for example, by this way:

send(socketClient, (void*)&userDataBuffer[i], sizeof(double), 0);