tcpip通讯 matlab,TCPIP通信

% A端:发送命令,并接收B端反馈

% A端IP为192.168.123.30, B端IP为192.168.123.10

clear;clc;close all;

% 构造服务器端tcpip对象

tcpipServer = tcpip('0.0.0.0',5001,'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

% 接收数据

recvRaw = fread(tcpipServer,nBytes/8,'double');

% 绘制接收数据图像

figure;

plot(recvRaw);grid on;

title('received signal from B');

% 关闭和删除连接对象

fclose(tcpipServer);

delete(tcpipServer);

% B端:收到指令后反馈1024点的正弦波叠加噪声

clear;clc;close all;

% 构造反馈数据

N = 1024;

t = [1:N]/N*4*pi;

signal = sin(t) + 0.05*rand(1,N);

figure;

plot(t,signal);

grid on;

title('signal on the end of B.')

% 构造客户端tcpip对象

tcpipClient = tcpip('192.168.123.30',5001,...

'NetworkRole','Client');%设置对象属性,A端的IP为192.168.123.30

set(tcpipClient,'OutputBufferSize',8*N); %设置缓存长度

set(tcpipClient,'InputBufferSize',1024); %设置缓存长度

set(tcpipClient,'Timeout',60); %设置连接时间为1分钟

%打开连接对象

fopen(tcpipClient);

% 等待接收命令

while(1)

nBytes = get(tcpipClient,'BytesAvailable');

if nBytes>0

break;

end

end

% 接收命令

receivedInstruction = fread(tcpipClient,nBytes,'int8');

disp(strcat('received instruction is: ',char(receivedInstruction')));

% 反馈数据

fwrite(tcpipClient,signal,'double');

% 关闭和删除连接对象

fclose(tcpipClient);

delete(tcpipClient);

这是您写的,我试了,把其中B端的IP换成我这里服务端电脑的IP,也是连接不上。也有错。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值