如何将 c++ 中的客户端 TCP 的替身列表发送到 Matlab 中的 TCP 服务器?

How to send a list of doubles as a client TCP in c++ to a TCP server in Matlab?

本文关键字:TCP Matlab 服务器 中的 替身 c++ 客户端 列表      更新时间:2023-10-16

我是 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 sentn"); 
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};

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

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

希望这有帮助,