问题
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?
回答1:
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.
回答2:
I found out what was happening - turns out the Mathworks documentation was incorrect.
Since we're sending data as doubles, you'll need to specify the data being sent to be encoded as doubles. When reading it back, remember to account for the fact that eight bytes represent one double.
Here's how the client code needed to be changed to:
fwrite(t, data, 'double');
Here's how the server receives it as doubles:
data = fread(t, t.BytesAvailable/8, 'double');
You need the t.BytesAvailable/8
to ensure that eight bytes are being interpreted as one value.
来源:https://stackoverflow.com/questions/57632576/matlab-tcp-ip-server-sockets-not-sending-accurate-data