一个简单的UDP广播示例,需要开三个会话。
会话多开参见上一篇。
先运行udp_client.m 后运行udp_server.m与udp_server2.m
1.udp_client.m
ipA = '255.255.255.255'; %A的IP地址和端口号
portA = 9091;
ipB = '255.255.255.255';%B的IP地址和端口号
portB = 9090;
%%得到默认广播地址
[~,hostName] = system('hostname');
% Convert hostname to fully-qualified domain name
[~,hostAddress] = resolvehost([strtrim(hostName) '.dhcp.mathworks.com']);
% Compute broadcast address. This assumes a subnet mask of 255.255.255.0,
% which implies that address xxx.xxx.xxx.255 is the broadcast address
expression = '(?<=\d+[.]\d+[.]\d+[.])\d+';
broadcastAddress = regexprep(hostAddress, expression, '255');
%%在端口广播地址
%发送地址为portB,接受为portA
udpTransmit=udp(broadcastAddress,portB,'LocalPort',portA);
%udpTransmit=udp(ipB,portB,'LocalPort',portA);
%set(udpTransmit,'OutputBufferSize',8192);%输出缓冲区容量,相当于设置窗口?
%set(udpTransmit,'TimeOut',10);%接收和发送前超时时间
udpTransmit.EnablePortSharing = 'on';
udpTransmit.Terminator = 'CR';
udpTransmit.BytesAvailableFcnMode = 'terminator';
udpTransmit.BytesAvailableFcn = @(~,~)fprintf('Message "%s" at %s\n', fgetl(udpSender), datestr(now));
fopen(udpTransmit);
data = sin(1:6);
fprintf(udpTransmit, data);
fclose(udpTransmit);
delete(udpTransmit);
clear ipLocal portTransmit_Local ipReceive_remote portReceive_Remote
close();
2.udp_Server1.m
portA=9090;
ipA='127.0.0.1';
portB=9090;
%A 接受, B 来自
udpReceive=udp(ipA,portA,'LocalPort',portB);
set(udpReceive,'TimeOut',30);
set(udpReceive,'InputBufferSize',8192);
udpReceive.EnablePortSharing = 'on';
fopen(udpReceive);
data = str2num(fscanf(udpReceive))
plot(data);
title('Server 1');
%pause(0.1)
clear ipA portA portB
fclose(udpReceive);
delete(udpReceive);
%close();
3.udp_server2.m
portA=10095;
ipA='127.0.0.3';
portB=9090;
%A 接受, B 来自
udpReceive2=udp(ipA,portA,'LocalPort',portB);
set(udpReceive2,'TimeOut',30);
set(udpReceive2,'InputBufferSize',8192);
udpReceive2.EnablePortSharing = 'on';
fopen(udpReceive2);
data2 = str2num(fscanf(udpReceive2))
plot(data2);
title('Server 2');
%pause(0.1)
clear ipA portA portB
fclose(udpReceive2);
delete(udpReceive2);
%close();