看板java
标 题Re: [问题] ServerSocket.accept() 要怎麽强制结束?
发信站无名小站 (Sat Jun 3 22:49:03 2006)
转信站ptt!ctu-reader!Spring!news.nctu!news.ntu!news.ee.ttu!netnews.csie.nctu
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;
}
※ 引述《[email protected]》之铭言:
> 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海