/*聊天室程序服务器端程序
监听连接的客户端
接受某客户端输入然后广播
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
public class Server{
public Server(int port) throws IOException{
ServerSocket server=new ServerSocket(port);
//不断循环接受客户端的连接
while(true)
{
Socket conn=server.accept();
DataInputStream in=new DataInputStream(conn.getInputStream());
String who=in.readUTF();
System.out.print(“Client “+”(IP:”+conn.getInetAddress()+”)”+who+” enter!”+”\n”);
//每次监听到连接请求就创建一个线程
ServerHander cn=new ServerHander(who,conn);
cn.start();
}
}
public static void main(String args[])throws IOException{
new Server(9001);
}
}
class ServerHander extends Thread{
Socket socket;
DataInputStream in;
DataOutputStream out;
String who;
//保存所有的客户端对象
protected static Vector clientlist=new Vector();
public ServerHander(String name,Socket socket)throws IOException
{
this.who=name;
this.socket=socket;
in=new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out=new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
}
public void run(){
try{
clientlist.addElement(this);
sendallclient(“Welcome “+who+” entered”);
while(true)
{
String msg=in.readUTF();
sendallclient(who+” said: “+msg);
}
}
catch(IOException e)
{
System.out.println(“Client exit or error.”);
}
finally{
clientlist.removeElement(this);
sendallclient(who+” left !”);
try
{
socket.close();
}
catch(IOException ex)
{
System.out.println(“Connection has been closed”);
}
}
}
//给客户端传递信息
protected static void sendallclient(String msg)
{
synchronized(clientlist){
Enumeration allclients=clientlist.elements();
while(allclients.hasMoreElements())
{
ServerHander serh=allclients.nextElement();
try{
serh.out.writeUTF(msg);
serh.out.flush();
}
catch(IOException exc)
{
serh.interrupt();
}
}
}
}
}