package QQ;
import java.io.*;
import java.net.*;
import java.util.*;
public class QQServer {
public static void main(String[] args){
ServerSocket ss=null;
Socket sock=null;
ArrayList al=new ArrayList();
try{
ss=new ServerSocket(1228);
while(true){
sock=ss.accept();
Server ser=new Server(al,sock);
Thread t=new Thread(ser);
al.add(ser);
t.start();
}
}
catch (Exception e){e.printStackTrace();}
finally{
if (ss!=null){
try{ ss.close(); } catch(IOException e){e.printStackTrace();}
}
}
}
}
class Server implements Runnable{
public ObjectInputStream in=null;
public ObjectOutputStream out=null;
private Socket s;
private ArrayList al;
private String name;
public Server(ArrayList al,Socket s){
this.al=al;
this.s=s;
}
public void setName(String s){
this.name=s;
}
public String getName(){
return this.name;
}
public void run(){
try{
out=new ObjectOutputStream(this.s.getOutputStream());
in=new ObjectInputStream(this.s.getInputStream());
while(true){
if (s.isClosed()) {
break;
}
else{
Object o=in.readObject();
if (o==null) continue;
ServerInfo si=(ServerInfo)o;
int type=si.getType();
if (si.getUser().equals("All") || type==ServerInfo.ADD || type==ServerInfo.DEL)
{
notiAll(si);
}
else noti(si);
if (type==ServerInfo.DEL){
s.close();
this.al.remove(this);
break;
}
if (type==ServerInfo.ADD){
Iterator it=al.iterator();
while(it.hasNext()){
Server ms=(Server)it.next();
String name=ms.getName();
ServerInfo si2=new ServerInfo(name+" entered!",name,ServerInfo.ADD);
out.writeObject(si2);
out.flush();
}
}
} //end else
} //end while
} //end try
catch(Exception e){e.printStackTrace();}
finally{
if(s!=null) {
try {s.close();}catch(Exception ex) {ex.printStackTrace();}
}
if(in!=null) {
try {in.close();}catch(Exception ex) {ex.printStackTrace();}
}
if(out!=null) {
try {out.close();}catch(Exception ex) {ex.printStackTrace();}
}
}
}
public ObjectOutputStream getWriter(){
return this.out;
}
private void notiAll(ServerInfo si) throws Exception{
String content=si.getContent();
if (si.getUser().equals("All")){
String c=si.getContent();
c=name+" said: "+c;
si.setContent(c);
}
if (si.getType()==ServerInfo.ADD) this.setName(si.getUser());
Iterator it=al.iterator();
while(it.hasNext()){
Server ms=(Server)it.next();
if (!(si.getUser().equals(ms.getName()))){
ObjectOutputStream pw=ms.getWriter();
pw.writeObject(si);
pw.flush();
}
} //end while
}
private void noti(ServerInfo si) throws Exception{
String user=si.getUser();
String content=si.getContent();
Iterator it=al.iterator();
while(it.hasNext()){
Server ms=(Server)it.next();
if (ms.getName().equals(user)){
String c=si.getContent();
c=name+" said: "+c;
si.setContent(c);
ObjectOutputStream pw=ms.getWriter();
pw.writeObject(si);
pw.flush();
}
}
}
}
评论4