0

We have batch files that my company likes to run overnight so I took our server(MatLab)/client(Java/Eclispe) code, that worked fine with single files, put a while true loop around everything and got it to work properly that way. The only problem we have it that the server always looks for a client, with the socket.accept() call, but if it has no clients to connect to it, it just sits there forever. To close the program we have to go to the task manager and force it closed.

So it there any way I could put a timer on accept so if no one tries to connect after a certain time, no more batch files to run, I can cancel the connect and shutdown the program.

1 Answers1

0

This code will allow you to set the timeout on accept()

private ServerSocket listener;  
    private int timeout;  
    private Thread runner;  
    private boolean canceled;  

    ...  

    // returns true if cancel signal has been received  
    public synchronized boolean isCanceled()  
    {  
        return canceled;  
    }  

    // returns true if this call does the canceling  
    // or false if it has already been canceled  
    public synchronized boolean cancel()  
    {  
        if ( canceled ) {  
            // already canceled due to previous caller  
            return false;  
        }  

        canceled = true;  
        runner.interrupt();  
        return true;  
    }  

    public void run()  
    {  
        // to avoid race condition (see below)  
        listener.setSoTimeout(timeout);  

        while ( ! isCanceled() ) {  
            // DANGER!!  
            try {  
                Socket client = listener.accept();  
                // hand client off to worker thread...  
            }  
            catch ( SocketTimeoutException e ) {  
                // ignore and keep looping  
            }  
            catch ( InterruptedIOException e ) {  
                // got signal while waiting for connection request  
                break;  
            }  
        }  

        try {  
            listener.close();  
        }  
        catch ( IOException e ) {  
            // ignore; we're done anyway  
        }  
    }  
Jon
  • 3,230
  • 1
  • 16
  • 28