c++ - 如何将双精度列表作为 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};
解决方案
默认情况下 fread 解释字节。因此,根据 fread 文档,您应该使用以下内容:
d = fread(t, t.BytesAvailable, 'double=>double');
希望这可以帮助,
推荐阅读
- javascript - 根据某些属性过滤嵌套数组
- c# - 我需要在我的代码中添加 int 变量,有什么想法吗?
- security - 私有应用的 OAuth2 流程和最佳实践
- html - 需要将丢失的 URL 重定向到新主机
- c# - 为什么 Code Map 不适用于 Unity 项目?
- javascript - 函数给我类型错误:无法读取未定义的属性“调整大小”
- python - 为什么我在这段代码中看到“KeyError: 'rating_count_total'”
- java - org.apache.kafka.common.errors.TimeoutException:使用 jaas SASL 配置身份验证获取 Kafka 集群的主题元数据时超时
- python - Python用列表中的单个字符串查找和替换多个字符串
- go - 多次分离和重用项目