在编写一个类的过程中,将matlab的两个实例连接在一起。实例将在单独的计算机上,但我目前正在1台计算机上进行测试。
目前,我能够在两个matlabs之间建立连接,并且能够在它们之间发送/接收消息。
代码:
classdef connectcompstogether<handle
properties
serverIP
clientIP
tcpipServer
tcpipClient
Port = 4000;
bsize = 8;
Message
end
methods
function gh = connectcompstogether(~)
% gh.serverIP = '127.0.0.1';
gh.serverIP = 'localhost';
gh.clientIP = '0.0.0.0';
end
function SetupServer(gh)
gh.tcpipServer = tcpip(gh.clientIP,gh.Port,'NetworkRole','Server');
set(gh.tcpipServer,'OutputBufferSize',gh.bsize);
fopen(gh.tcpipServer);
display('Established Connection')
end
function SetupClient(gh)
gh.tcpipClient = tcpip(gh.serverIP,gh.Port,'NetworkRole','Client');
set(gh.tcpipClient,'InputBufferSize',gh.bsize);
set(gh.tcpipClient,'Timeout',30);
fopen(gh.tcpipClient);
display('Established Connection')
end
function CloseClient(gh)
fclose(gh.tcpipClient);
end
end
methods
function sendmessage(gh,message)
fwrite(gh.tcpipServer,message,'double');
end
function recmessage(gh)
gh.Message = fread(gh.tcpipClient,gh.bsize);
end
end
end
matlab 1
gh = connectcompstogether;
gh.SetupServer();
gh.sendmessage(555);
matlab 2
gh = connectcompstogether;
gh.SetupClient();
gh.recmessage();
发送的消息是一个8位的双字节555。然而,当查看收到的消息时,发现它是一个矩阵
64
129
88
我不明白发生了什么,因为我下面的例子没有这个问题。
以及添加上下文。我正试图通过TCP-IP连接两个matlabs,这样我就可以用另一个实例控制一个实例。我的计划是让第二个matlab等待命令代码,并在第一个matlab请求时执行指定的函数。
tcpip/frad默认精度为uchar,因此默认情况下fread将输出8位无符号整数的列数组。
您需要指定需要一个双精度:
%size divided by 8, as one 8-byte value is expected rather than 8 1-byte values
gh.Message = fread(gh.tcpipClient,gh.bsize/8,'double');
或者将uint8数组类型转换为双重:
rawMessage = fread(gh.tcpipClient,gh.bsize); %implicit: rawMessage is read in 'uchar' format
% cast rawMessage as uint8 (so that each value is stored on a single byte in memory, cancel MATLAB automatic cast to double)
% then typecast to double (tell MATLAB to re-interpret the bytes in memory as double-precision floats)
% a byteswap is necessary as bytes are sent in big-endian order while native endianness for most machines is little-endian
gh.Message = swapbytes(typecast(uint8(rawMessage),'double'));