首页 > 解决方案 > 如何将双精度列表作为 C++ 中的客户端 TCP 发送到 Matlab 中的 TCP 服务器?

问题描述

我是 C++ 和 Matlab 的新手,我想将一些数据从树莓派发送到我的 Matlab。此数据是双打列表。这是我到目前为止的代码。C++(客户端):

#include <stdio.h> 
#include <stdlib.h>
#include <sys/socket.h> 
#include <arpa/inet.h> 
#include <unistd.h> 
#include <string.h> 
#define PORT 8080 

int main(int argc, char const *argv[]) 
{ 
    int sock = 0; 
    struct sockaddr_in serv_addr; 
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) 
    { 
        printf("\n Socket creation error \n"); 
        return -1; 
    } 

    serv_addr.sin_family = AF_INET; 
    serv_addr.sin_port = htons(PORT); 

    // Convert IPv4 and IPv6 addresses from text to binary form 
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)  
    { 
        printf("\nInvalid address/ Address not supported \n"); 
        return -1; 
    } 

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) 
    { 
        printf("\nConnection Failed \n"); 
        return -1; 
    } 

    double x[] = {10, 13.878, 3.09, 43, 5.0, 2, 342.42, 4};
    send(sock, x, sizeof(x), 0);
    close(sock);
    printf("Message sent\n"); 

    return 0; 
} 

Matlab(服务器):

t = tcpip('0.0.0.0', 8080, 'NetworkRole', 'server');
fopen(t);
data = 0;
while(data ~= 1)
data = fread(t, t.BytesAvailable);
disp(data);
end
disp("fim do codigo");
fclose(t);

Matlab 中的输出为:

     0
     0
     0
     0
     0
     0
    36
    64
   168
   198
    75
    55
   137
   193
    43
    64
   184
    30
   133
   235
    81
   184
     8
    64
     0
     0
     0
     0
     0
   128
    69
    64
     0
     0
     0
     0
     0
     0
    20
    64
     0
     0
     0
     0
     0
     0
     0
    64
    31
   133
   235
    81
   184
   102
   117
    64
     0
     0
     0
     0
     0
     0
    16
    64

Error using icinterface/fread (line 160)
SIZE must be greater than 0.

Error in servidor (line 5)
data = fread(t, t.BytesAvailable);

C++ 代码中的列表只是一个测试,它在 Matlab 中接收到错误的数字。有人可以帮我正确发送此列表吗?

编辑:

我尝试将我的fread命令更改data = fread(t, t.BytesAvailable, 'double=>double');为如下所示,但它不起作用,'double=>double'不是正确的名称,我只尝试了'double'而不是'double=>double'. 新的输出是:

    Warning: The specified amount of data was not returned within the Timeout period.
'tcpip' unable to read all requested data. For more information on possible reasons, see TCPIP Read Warnings. 
   1.0e-37 *

   -0.0000
   -0.2242
    0.0000
    0.0000

Warning: The specified amount of data was not returned within the Timeout period.
'tcpip' unable to read any data. For more information on possible reasons, see TCPIP Read Warnings. 
fim do codigo

我改变的另一件事是列表的大小,现在我只是想发送这个列表:double x[4] = {13.878, 3.09, 5.0, 342.42};

标签: c++matlabtcpraspberry-pi

解决方案


默认情况下 fread 解释字节。因此,根据 fread 文档,您应该使用以下内容:

d = fread(t, t.BytesAvailable, 'double=>double');

希望这可以帮助,


推荐阅读