MATLAB脚本调用​TCP/IP函数时不​报错,但在命令行窗口​调用或APP设计工具​中调用会报错,这是为​什么?

13 views (last 30 days)
Wenchao
Wenchao on 8 Dec 2025
APP设计工具内的TCP/IP函数:
methods (Access = private)
% 用于数据传输(指令及反馈,TCP/IP)
function sensorFbk = dataTransmission(app, enable, controlMode, triggerEdge, cmdData, alarmReset, runTime)
% PLC连接信息
plcIP = "192.168.58.100";
plcPort = 8081;
% 初始化或检查连接
if isempty(app.tcpClient) || ~isvalid(app.tcpClient) || ...
~isequal(app.connectionInfo, [plcIP, plcPort])
% 关闭旧连接
if ~isempty(app.tcpClient) && isvalid(app.tcpClient)
delete(app.tcpClient);
end
app.tcpClient = [];
% 创建新连接
try
app.tcpClient = tcpclient(plcIP, plcPort, 'Timeout', 10);
app.connectionInfo = [plcIP, plcPort];
catch ME
error('PLC连接失败: %s', ME.message);
end
end
% 准备发送数据
sendData = int32(zeros(1, 14));
sendData([1, 8]) = enable;
sendData([2, 9]) = controlMode;
sendData([3:4, 10]) = triggerEdge;
sendData([5:7, 11:13]) = cmdData;
sendData(14) = alarmReset;
% 发送数据(带错误处理)
try
write(app.tcpClient, sendData, "int32");
catch
% 发送失败,尝试重连一次
delete(app.tcpClient);
app.tcpClient = [];
app.tcpClient = tcpclient(plcIP, plcPort, 'Timeout', 10);
write(app.tcpClient, sendData, "int32");
end
% 使系统稳定运行一段时间
pause(runTime);
% 读取返回数据
sensorFbk = read(app.tcpClient, 7, "int32");
flush(app.tcpClient);
end
end
此时,内部回调函数调用该函数时会报如下错误:
错误使用 AlgorithmIntegration/JointFrictionDataSendButtonPushed (第 2487 行)
PLC连接失败: Cannot create a communication link with the remote server. Please check the input arguments(ADDRESS and PORT) and make sure the server is running.
Additional Information: ����Ŀ�����������ܾ����޷����ӡ�
请参阅 相关文档 了解故障排除步骤。

Answers (0)

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!