2013-09-28 42 views
-1

我有一個Runnable類,它正在等待Socket連接。我想添加JButton,導致它停止等待連接並退出循環。在while循環中等待連接時停止Runnable

這裏是環

volatile boolean finished = false; 

while (!finished) { 
    System.out.println("Server Started...."); 
    clientSocket = serverSocket.accept(); // want to skip this line when the button is pressed 
    if (!clientSocket.isClosed() && ServerSettings.getServerStatus() != -1) { 
     // start communication 
    } else { 
     // close connection 
    } 
} 

我找了這個問題,並發現a solution here退出循環。但是這並不能完全解決我的問題。我可以更改finished變量的值,但爲了檢查新值,我仍然需要跳過等待一次。

任何幫助是可觀的。

+0

順便說一句:true &&!finished ==!finished。 – Sinkingpoint

+0

@Quirliom:謝謝,我更新了這篇文章。 –

回答

0

您可以撥打close()方法。這將阻止連線的w。。

+0

那麼,我是否需要在點擊時拋出'SocketException',因爲它正在等待? –

+0

是的。你應該拋出SocketException。 – Masudul

0

而不是ServerSocket,使用ServerSocketChannel,這是accept()方法不會阻止。從技術文檔:

public abstract SocketChannel accept() throws IOException

接受到此通道套接字的連接。

如果此通道處於非阻塞模式,那麼如果沒有掛起的連接,此方法將立即返回null。