packagecom.swift;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.EOFException;importjava.io.IOException;importjava.net.BindException;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;public classChatServer {boolean started = false;
ServerSocket ss= null;
Socket s= null;
List clients=new ArrayList();public static voidmain(String[] args) {newChatServer().fun();
}private voidfun() {try{
ss= new ServerSocket(8888);
started= true;
}catch(BindException e) {
System.out.println("端口使用中......");
}catch(IOException e1) {
e1.printStackTrace();
}try{while(started) {
s=ss.accept();
System.out.println("a client connected success");
Client c= newClient(s);newThread(c).start();
clients.add(c);
}
}catch(EOFException e) {
System.out.println("client has closed.");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
ss.close();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}class Client implementsRunnable {privateSocket s;privateDataInputStream dis;privateDataOutputStream dos;private boolean connected = false;publicClient(Socket s) {this.s =s;try{this.dis = newDataInputStream(s.getInputStream());this.dos = newDataOutputStream(s.getOutputStream());
connected= true;
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}private voidsend(String str) {try{
dos.writeUTF(str);
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
};
}
@Overridepublic voidrun() {try {//注意:要包括while循环,如果try在while循环里,则出现socket closed异常
while(connected) {
String str=dis.readUTF();
System.out.println(str);for(int i=0;i
Client c=clients.get(i);
c.send(str);
}//for(Iterator it=clients.iterator();it.hasNext();) {//Client c=it.next();//方法二,不可取,有同步锁//c.send(str);//}//Iterator it=clients.iterator();//while(it.hasNext()) {//Client c=it.next();//方法三,不可取,有同步锁,修改需要加锁(此时没修改)//c.send(str);//}
}
}catch(IOException e) {
e.printStackTrace();
}finally{if (dis != null) {try{
dis.close();
}catch(IOException e) {
e.printStackTrace();
}
}if (s != null) {try{
s.close();
}catch(IOException e) {
e.printStackTrace();
}
}if(dos!=null) {try{
dos.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
}