0

私の会社が夜間に実行するのが好きなバッチファイルがあるので、単一のファイルで問題なく動作するサーバー(MatLab)/クライアント(Java/Eclispe)コードを取得し、すべてにwhile trueループを配置し、そのように適切に動作させました. 唯一の問題は、サーバーが socket.accept() 呼び出しを使用して常にクライアントを探しますが、接続するクライアントがない場合、サーバーは永遠にそこに留まることです。プログラムを閉じるには、タスク マネージャーに移動して強制的に閉じる必要があります。

したがって、タイマーを受け入れる方法があるので、一定時間後に誰も接続を試みず、実行するバッチファイルがなくなった場合、接続をキャンセルしてプログラムをシャットダウンできます。

4

1 に答える 1

0

このコードにより、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  
        }  
    }  
于 2012-06-26T16:50:14.550 に答える