日期:2014-05-20 浏览次数:20696 次
import java.util.*; import java.net.*; import java.io.*; public class Server{ public static final int port=10000; public static final Vector users=new Vector(); public static void main(String args[]){ ServerSocket server=null; try{ server=new ServerSocket(port); System.out.println("Server start up on port :"+port); while(true){ Socket s=server.accept(); User user=new User(s); user.start(); } }catch(Exception e){ e.printStackTrace(); }finally{ if(server!=null&&!server.isClosed()){ try{server.close();}catch(Exception e){} } } } } class User extends Thread{ private Socket s; private String userName; private InetAddress ip; public User(Socket s){ this.s=s; } public void run(){ try{ InputStream input=s.getInputStream(); OutputStream output=s.getOutputStream(); BufferedReader buf=new BufferedReader(new InputStreamReader(input)); PrintWriter pw=new PrintWriter(new OutputStreamWriter(output),true); pw.println("welcome u ,enter your name :"); userName=buf.readLine(); Server.users.add(this); sendAll(userName+" has join us ");; long t=0; while(true){ String line=buf.readLine(); long s=System.currentTimeMillis(); if((s-t)/1000<3){ pw.println("flush denied "); continue; } t=s; if(line==null||line.trim().length()==0){ pw.println("flush denied "); continue; } if(line.equals("bye")){ sendAll(userName+" leave us "); Server.users.remove(this); break; } sendAll(userName+" said :"+line); } }catch(Exception e){ //e.printStackTrace(); }finally{ if(s!=null)try{s.close();}catch(Exception e){} } } public synchronized void sendMessage(String message){ try{ PrintWriter pw=new PrintWriter(new OutputStreamWriter( s.getOutputStream())); pw.println(message); pw.flush(); }catch(Exception e){} } public void sendAll(String message){ Iterator it=Server.users.iterator(); while(it.hasNext()){ User user=(User)it.next(); user.sendMessage(message); } } }