MATLAB: Cannot communicate more than twice between server and client

Instrument Control ToolboxMATLABtcpip

I want to construct more than twice communication between server and client.
I make two code Client and Server.
I achieve a single communication, but I cannot second communication.
Error message is "icinterface/fopen (line 83) Unsuccessful open: Connection refused: connect"
Client Code :
clc;
clear ;
close all;
% Configuration and connection

client = tcpip('localhost',30000,'NetworkRole','client');
disp('Wating for connection');
% Open socket and wait before sending data
fopen(client);
disp('Connection OK');
disp('Send Data')
fwrite(client, 'test')
disp('Complete send')
fclose(client);
delete(client);
clear client
Server Code :
%% TCP/IP Receiver
% Clear console and workspace
try
delete(server);
clear server
end
echotcpip('off');
close all;
clear all;
clc;
% Configuration and connection
disp ('Receiver started');
server=tcpip('localhost', 30000,'NetworkRole','server');
set(server, 'Timeout',inf);
set(server, 'InputBufferSize', 300000);
% Wait for connection
disp('port open. Waiting for connection');
fopen(server);
while true
while server.BytesAvailable == 0
end
% Read data from the socket
DataReceived=fread(server,server.BytesAvailable);
disp(strcat(char(DataReceived)'));
disp('Connection OK');
disp('complete read data');
end
fclose(server);
disp('port closed');

Best Answer

If you need multiple simultaneous connections, they will have to be on different ports.
One strategy in common use (by some of the key daemons, but not so much with user programs) is to publish a port for the client to make the connection to (e.g., the 30000), but instead of holding on to that port for the entire conversation, instead the server creates a new listener on another port, and responds to the client telling it what port the listener was created on, and then ends the connection. All of the clients need to talk to the same master port to get told what port the conversation will take place on, but those conversations are short and any refused connection can be retried a short time later to get the system a chance to finish the previous (short) conversation.
Related Question