需求:
c++做客户端调用matlab处理数据,获取matlab返回的数据集合,但是希望matlab以服务的形式一直挂载使用,这里提供一个简单的方法,在tcp服务上再套一层while(1)即可,如何有更好的方法欢迎在评论区讨论。
while(1)
port = 9010;
% 构造服务器端tcpip对象
tcpipServer = tcpip('0.0.0.0',port,'NetWorkRole','Server');
set(tcpipServer,'Timeout',10);
N = 1024;
set(tcpipServer,'InputBufferSize',8*N);
set(tcpipServer,'OutputBufferSize',1024);
% 打开连接对象
fopen(tcpipServer);
% 发送指令
instruction = 'Please send back a signal.';
fwrite(tcpipServer,instruction,'int8');
disp('Instruction sending succeeds.');
numSent = get(tcpipServer,'valuesSent');
disp(strcat('Bytes of instruction is :',num2str(numSent)));
% 等待接收数据
while(1)
nBytes = get(tcpipServer,'BytesAvailable');
if nBytes > 0
break;
end
end
% 接收数据
receivedInstruction = fread(tcpipServer,nBytes,'int8');
disp(strcat('received instruction is: ',char(receivedInstruction')));
% 关闭和删除连接对象
fclose(tcpipServer);
delete(tcpipServer);
end
参考: