Why does not this program code work in the third TCP communication?

조회 수: 1 (최근 30일)
Naoya Inoue
Naoya Inoue . 2018년 9월 5일
댓글: Greg . 2018년 9월 5일
I create TCP server that can communicate many times. But, following code cannot work my target.Best Regars. I make SERVER.m and CLIENT.m. Further, I run each file by two matlab on same PC.
% SERVER
clear all
clc
disp('Server Stated');
server = tcpip('0.0.0.0', 30000, 'NetworkRole', 'server');
while true
disp('waiting for connection');
fopen(server);
disp('Connection OK');
data = fread(server, server.BytesAvailable);
disp('read data');
disp(char(data));
fclose(server);
disp('end connection');
end
% Client
clear all
clc
data = 'H';
disp('client Stated');
client = tcpip('localhost', 30000, 'NetworkRole', 'client');
disp('waiting for connection');
fopen(client);
disp('Connection OK');
fwrite(client, data);
disp('write data');
fclose(client);
  댓글 수: 1
Greg
Greg 2018년 9월 5일
Are you seeing any of the disp output from the Client after the Server is started?

댓글을 달려면 로그인하십시오.

답변 (1개)

Greg
Greg 2018년 9월 5일
Take the fopen and fclose out of the while loop. Repeatedly opening and closing the tcpip obj is unnecessary, and usually extremely costly (performance). Further, since there is no wait time for the client to send a message between the open and close, you have practically 0 chance of catching the message.
  댓글 수: 2
Greg
Greg 2018년 9월 5일
Now you need some logic to prevent reading if there are no bytes available.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming Utilities에 대해 자세히 알아보기

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by