2012年5月10日 星期四

2012/05/10


try catch 用法    參考資料:http://blog.yslifes.com/archives/636

While迴圈         參考資料: http://caterpillar.onlyfun.net/Gossip/JavaGossip-V1/LoopWhile.htm

try裡的敍述句有可能會丟出例外資訊 ( Exception ) ,而丟出的例外資訊 ( Exception ) 型態就可以由catch來取得,做適當的處理。finally則是在try catch完成後會執行的動作,一般都是使用在關閉或則除物件等。
ps.catch取得例外需由小範圍而後大範圍,例如java.lang.NullPointException則需寫在Exception前面,因為NullPointException所能處理的範圍比Exception還小。

import java.net.*;
import java.io.*;
public class Server {
   public final static int myPort=20; // 使用port 20
   public static void main(String args[]) {
      ServerSocket ss;
      Socket sc;
      PrintWriter op;
try {
  ss = new ServerSocket(myPort);
  try {
    while (true) {
sc = ss.accept(); // 等待建立連線
op = new PrintWriter(sc.getOutputStream());
op.println("Hi! There!");
op.flush(); // 很重要, 不要漏掉
sc.close();
}
  }
  catch (IOException e) {
ss.close();
System.err.println(e);
}
}
catch (IOException e) {
System.err.println(e);
}
}
}










一台server兩台client