Sending floating point number from server to client

后端 未结 3 876
醉酒成梦
醉酒成梦 2021-01-15 10:26

I am using TCP/IP socket programming. I have a floating point value stored in a variable ret_val in my server cod

相关标签:
3条回答
  • 2021-01-15 10:54
    float f = ...;
    size_t float_size = sizeof(float);
    const char* buffer = (const char *) &f;
    send(mySocket, buffer, float_size, 0);
    

    This code will work fine if both the server and client use the same platform. If the platforms are different, you will have to negotiate message sizes and endianess explicitly.

    0 讨论(0)
  • 2021-01-15 11:13

    Use a textual representation ?

    char buf[32] ; 
    snprintf(buf,sizeof buf,"%f",ret_val); 
    write(fd,buf,strlen(buf));
    

    You can read that string and parse it back again with sscanf. (Maybe even make it line terminated - "%f\n" - so you'll know when the number ends.)

    The direct approach is to simply

    write(fd,&ret_val,sizeof ret_val);
    

    In both cases you should check the return value of write and take proper action if an error occurs, or write() wrote less bytes than you told it to.

    0 讨论(0)
  • 2021-01-15 11:16

    If you know that both client and server are the same platform etc., you can simply use sizeof(float) to determine your buffer size and copy that many bytes from the address of your float.

    float number = 123.45;
    send(sockfd, &number, sizeof(float),0);
    

    As soon as your client/server are different platforms/different languages etc. you'll have to start worrying about how to portably encode the float. But for a simple approach, the above will work fine.

    0 讨论(0)
提交回复
热议问题