[問題] ServerSocket.accept() 要怎麼強制結束?
Hi,
假設我要寫一個允許 multi-client 的 server,
一般應該會把程式分成至少三條 thread:
1. 服務單一 client 的 thread
2. 等待 client 連線的 thread
3. Main thread, 處理 UI
我希望使用者在 UI 裡輸入 'exit' 時就結束整個程式 (結束所有 thread),
所以我寫了這樣的程式 (以下程式碼只是大概寫出來的, 不能編譯):
// 服務單一 client
class ServeOneClient extends Thread {
Socket sock;
public ServeOneClient(Socket s) {
sock = s;
}
public void run() {
// 這裡放服務 client 的程式碼.....
}
}
// 等待 client 的連線, 等到後就丟給 ServeOneClient 處理,
// 然後自己再繼續等待 client
class ServerListener extends Thread {
volatile boolean stopped = false;
ServerSocket ss = new ServerSocket(1234);
public void run() {
while (true) {
Socket s = ss.accept();
(new ServeOneClient(s)).start();
if (stopped)
break;
}
}
}
// Main thread, 處理 UI
class Main {
public static void main(String[] args) {
ServerListener listener = new ServerListener();
listener.start();
while (true) {
// ........
// 其他處理 UI 的程式碼...
// ......
if (使用者輸入 'exit' 指令) {
listener.stopped = true;
listener.join();
break;
}
}
}
}
問題是 ServerListener 這條 thread 裡的 ServerSocket.accept()
會一直 hang 在那裡, 直到有 client 連進來才回傳,
導致無法馬上執行到之後的 if (stopped) 那行程式碼,
請問我要怎麼寫, 才能讓 main 去結束 ServerListener? (除了用 System.exit(0))
謝謝!!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.132.133.199
※ 編輯: eliang 來自: 220.132.133.199 (06/02 13:02)
討論串 (同標題文章)