background image

     for(int i=0; i<clients.size(); i++){
      Client c = clients.get(i);  //取客户端
      c.send(str);  
     }
     /*     另外两种方法,但不适用,它会锁定服务端
     for(Iterator<Client> it = clients.iterator(); it.hasNext();){
      Client c = it.next();
      c.send(str);
     }
     
     Iterator<Client> it = clients.iterator();
     while(it.hasNext()){
      Client c = it.next();
      c.send(str);
     }
     */
    }
   } catch (EOFException e){   //readUTF()阻塞式方法,所以关闭客户端会抛异常
    System.out.println("Client closed!");
   } catch (IOException e) {
    e.printStackTrace();
   } finally {
    try {
     if(dis != null) dis.close();
     if(dos != null) dos.close();
     if(s != null) {
      s.close();
      s = null;//更严格的方法,等于空就没人去用了,垃圾收集器就回收走
     }
    } catch (IOException e) {
     e.printStackTrace();
    } 
   }
  }
 }
}

客户端:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;