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

1 visualización (últimos 30 días)
Naoya Inoue
Naoya Inoue el 5 de Sept. de 2018
Comentada: Greg el 5 de Sept. de 2018
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 comentario
Greg
Greg el 5 de Sept. de 2018
Are you seeing any of the disp output from the Client after the Server is started?

Iniciar sesión para comentar.

Respuestas (1)

Greg
Greg el 5 de Sept. de 2018
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 comentarios
Naoya Inoue
Naoya Inoue el 5 de Sept. de 2018
Is Your Idea Fllowing Code ?
disp('waiting for connection');
fopen(server);
while true
disp('Connection OK');
data = fread(server, server.BytesAvailable);
disp('read data');
disp(char(data));
end
fclose(server);
disp('end connection');
disp error message on Server Command window.
ERROR: icinterface/fread (line 160)
SIZE must be greater than 0.
ERROR: matlab_server_ex (line 27)
data = fread(server, server.BytesAvailable);
Greg
Greg el 5 de Sept. de 2018
Now you need some logic to prevent reading if there are no bytes available.

Iniciar sesión para comentar.

Categorías

Más información sobre Programming Utilities en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by