Close connection associated with a tcpip server

12 次查看(过去 30 天)
I have a tcpserver object listening on a port. I'd like to close the socket when I'm done so I can reuse it without having to quit all the way out of Matlab.
Docs suggest "clear mytcpserver" should do the job, but this doesn't appear to be the case. If I try and create a new tcpserver object listening on the same port after clearing the previous one, I get a "Address already in use" error. And indeed, lusing netstat, I can see matlab is still listening on the port even after running "clear" on the associated tcpserver object.

回答(1 个)

Chetan
Chetan 2023-9-28
I understand that you are experiencing difficulties when closing the TCP server connection. According to the documentation, the "clear" function is supposed to close the TCP server. Alternatively, you can try using the "fclose" and "delete" functions explicitly to manually close the connection.
For more details about the "tcpserver" function, please refer to the following MathWorks documentation:
Here is a sample code that demonstrates how to manually close the TCP server so that the same port can be used again:
% Create TCP server0
port = 1234; % Specify the port number
mytcpserver = tcpserver("0.0.0.0", port); % Create the TCP server object
disp("TCP server created successfully.");
% Attempt to create another server on the same port (will result in an error)
try
mytcpserver2 = tcpserver("0.0.0.0", port);
catch exception
disp("Error: " + exception.message);
end
% Close and release the TCP server
fclose(mytcpserver); % Close the socket explicitly
delete(mytcpserver); % Delete the tcpserver object from memory
%clear mytcpserver; % Clear the variable name from the workspace
%tcpserver("0.0.0.0", port)
I hope these suggestions help you resolve the issue you are facing.

标签

Community Treasure Hunt

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

Start Hunting!

Translated by