I am using the example from the Matlab R2019A documentation about TCP/IP connection to send data back and forth two Matlab instances over TCP.
https://www.mathworks.com/help/instrument/communicate-using-tcpip-server-sockets.html
I have a TCP client (client.m) file written as:
data = sin(1:64);
plot(data);
t = tcpip('localhost', 30000, 'NetworkRole', 'client');
fopen(t)
fwrite(t, data)
and a TCP server (server.m) file written as:
t = tcpip('0.0.0.0', 30000, 'NetworkRole', 'server');
fopen(t);
data = fread(t, t.BytesAvailable);
plot(data);
However, the data being sent from the client is a double
array, but the data received is a integer
array.
The data sent looks like the following plot:
While the data received looks like the following plot:
How can I ensure that the data that is being sent is received exactly as it is?
I think what you need to do, is to specify also the precision of the data being send and received (to ensure the bytes are interpreted correctly):
% to send
fwrite(t, data, 'double');
% to receive 1000 doubles
data = fread(t, 1000, 'double');
This is at least what Mathworks suggests. See section Reading binary data
, as well as docs for fread and fwrite.