由于毕设需要,需要用MATLAB写一个上位机程序。由于本人没有接触过MATLAB APP Designer,所以将功能分解逐步实现,本帖记录实现TCP连接以及数据收发功能。

UI设计:
-
1个多行文本框(Text Area):显示接收的原始文本(命名为
LogTextArea)。 -
1个编辑字段(Edit Field):输入服务器IP(命名为
IPEditField)。 -
1个编辑字段(Edit Field):输入端口号(命名为
PortEditField)。 -
1个按钮(Button):连接/断开服务器(命名为
ConnectButton)。 -
1个按钮(Button):清空日志(命名为
ClearButton)。
function ConnectButtonPushed(app, event)
if ~app.isConnected
% 获取输入的IP和端口
ip = app.IPEditField.Value;
port = str2double(app.PortEditField.Value);
% 修正验证逻辑
if isnan(port) || port < 1 || port > 65535
uialert(app.UIFigure, '端口号必须为1-65535之间的整数', '错误');
return;
end
try
app.tcpClient = tcpclient(ip, port, 'Timeout', 5);
app.isConnected = true;
app.ConnectButton.Text = '断开';
% 启动异步数据接收(按字节流读取)
configureCallback(app.tcpClient, "terminator", @(src, ~) app.TCPDataCallback(src));
app.LogTextArea.Value = "TCP连接成功!";
catch ME
uialert(app.UIFigure, ['连接失败: ' ME.message], '错误');
end
else
% 断开连接
clear app.tcpClient;
app.isConnected = false;
app.ConnectButton.Text = '连接';
app.LogTextArea.Value = [app.LogTextArea.Value; 'TCP已断开'];
end
end
% TCP数据接收回调函数
function TCPDataCallback(app, src)
if isvalid(src)
data = readline(src); % 读取一行文本
% 将新数据追加到文本框末尾
app.LogTextArea.Value = [app.LogTextArea.Value; data];
% 自动滚动到最新行
app.LogTextArea.scroll('bottom');
end
end
% 清空日志按钮回调
function ClearButtonPushed(app, event)
app.LogTextArea.Value = ""; % 清空文本框
end
连接回环网络


设置网络IP地址


在SSCOM开启TCP 服务器侦听

更改APP的IP地址与端口号,点击连接成功连接到目标服务器

服务器发送数据,APP可以正常接收

在完成数据接收功能后,增加数据发送功能

发送按键回调函数
% Value changed function: SendButton
function SendButtonValueChanged(app, event)
if app.isConnected
dataToSend = app.SendEditField.Value; % 获取要发送的文本
if ~isempty(dataToSend)
try
% 确保数据是字符串格式
if ~ischar(dataToSend) && ~isstring(dataToSend)
dataToSend = char(dataToSend);
end
% 发送数据
fprintf(app.tcpClient, '%s\n', dataToSend);
% 在日志中显示发送的数据
app.LogTextArea.Value = [app.LogTextArea.Value;
sprintf('[发送] %s', dataToSend)];
app.LogTextArea.scroll('bottom');
catch ME
app.LogTextArea.Value = [app.LogTextArea.Value;
sprintf('[发送错误] %s', ME.message)];
end
end
else
uialert(app.UIFigure, '请先建立TCP连接', '错误');
end
end
APP发送数据

服务器可以正常接收


1万+

被折叠的 条评论
为什么被折叠?



