Re: [問題] ServerSocket.accept() 要怎麼強制結束?

看板java作者時間19年前 (2006/06/04 02:01), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
Thread would not be in running state if they are in blocking I/O just like socket.accept() By using ServerSocketChannel instead of ServerSocket, you could able to interrupt the blocking I/O. However, if you do not want to implement much changes on your code, you can play a little trick like this : //new added stop thread method in ServerListener class public void stop() { try { ss.close(); // ss = ServerSocket } catch (IOException ex) { //error occur } stopped = true; } ※ 引述《eliang.bbs@ptt.cc》之銘言: > 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)) > 謝謝!! -- 夫兵者不祥之器物或惡之故有道者不處君子居則貴左用兵則貴右兵者不祥之器非君子 之器不得已而用之恬淡為上勝而不美而美之者是樂殺人夫樂殺人者則不可得志於天下 矣吉事尚左凶事尚右偏將軍居左上將軍居右言以喪禮處之殺人之眾以哀悲泣之戰勝以 喪禮處之道常無名樸雖小天下莫能臣侯王若能守之萬物將自賓天地相合以降甘露民莫 之令而自均始制有名名亦既有夫亦將知止知止可以不殆譬道之在天下猶 tm.net.my
文章代碼(AID): #14WSvl00 (java)
文章代碼(AID): #14WSvl00 (java)