简体   繁体   中英

How to send double-type data via TCP/IP Winsock

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);                
                    }

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM