0

I have some code like the below, using java sockets from matlab. I don't think the solution needs to be matlab-specific though...

Problem: if I hit debug-quit before the socket can get closed by server_socket.close, it stays dangling/open. The only workaround that seems to work is stopping and restarting matlab, which I guess kills the background socket. How can I more generally close the ServerSocket, if it is left open by this function?

function server_socket = my_server( opts ) 
    % Run the server, my_server.m
    import java.net.ServerSocket
    import java.io.*
    server_socket = ServerSocket(6001);
        server_socket.setSoTimeout(5000);
        io_socket = server_socket.accept(); 
        fprintf(1, 'Client connected\n');
          % DO STUFF 1
          BreakPointHere = 1; 
          % DO STUFF 2
        % clean up
        server_socket.close; % badness if 'dbquit' before this
        io_socket.close;

end

I've tried googling for this but am not quite sure what keywords to use and there is information-overload with regard to java sockets...

EDIT: One solution is to make this a script instead of a function (i.e. delete the first line and last 'end'). That way the server_socket persists after debug kill. But I'd like to understand better where the sockets are handled, and don't want all the other variables to persist necessarily.

peter karasev
  • 2,508
  • 1
  • 28
  • 38
  • 3
    Check out the second answer, it is relevant in your case as well : http://stackoverflow.com/questions/8847866/how-can-i-close-files-that-are-left-open-after-an-error/8847870#8847870 – Andrey Rubshtein Sep 19 '12 at 13:51
  • 1
    I would recommend `onCleanup`, as per this: http://stackoverflow.com/questions/1098149/how-do-you-handle-resources-in-matlab-in-an-exception-safe-manner-like-try – Edric Sep 19 '12 at 14:04
  • cool the onCleanup mostly does it... any idea though, how to force-close the socket after it gets left open? Is it running as a child process under matlab or something like that? – peter karasev Sep 20 '12 at 05:55
  • The socket does not persist when you exit the function, but since Java has no destructors, it is not properly closed. You must take care of this yourself, e.g. in the cleanup function. – angainor Sep 20 '12 at 09:46

0 Answers0