MATLAB UDP-广播 简单例子

来源:互联网 发布:矩阵的奇异值是什么 编辑:程序博客网 时间:2024/05/20 16:35

一个简单的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 addressexpression = '(?<=\d+[.]\d+[.]\d+[.])\d+';broadcastAddress = regexprep(hostAddress, expression, '255');%%在端口广播地址%发送地址为portB,接受为portAudpTransmit=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_Remoteclose();

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  portBfclose(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  portBfclose(udpReceive2);delete(udpReceive2);%close();
0 0
原创粉丝点击