import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean stat = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();//用于存客户端
public static void main(String[] args) {
new ChatServer().start();
}
public void start(){
try {
ss = new ServerSocket(8888);
stat = true;
} catch(BindException e){ //Sever端已经运行,当重复运行时抛异常
System.out.println("端口正在使用中。。。。");
System.out.println("请关掉相关程序并重新运行服务器!"); //还会抛别的异常,所以直接关闭窗口
System.exit(0);
} catch(IOException e) {
e.printStackTrace();
}
try{
while(stat){
Socket s = ss.accept();
System.out.println("a client connected!" ); //测试语句写在最左边,以后没用可以删除或注掉
Client c = new Client(s); //每建立一个客户端,就new一个客户端对象,启动一个线程
new Thread(c).start();
clients.add(c); //勿忘写,将每个客户端加入到容器里
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis;
private DataOutputStream dos;
private boolean cont = false;
public Client(Socket s){
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());//初始化
dos = new DataOutputStream(s.getOutputStream());
cont = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str){ //用于发送给客户端
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this); //移除那个退出的对象
System.out.println("一个客户退出了");
//e.printStackTrace();
}
}
public void run() {
try{
while(cont){
String str = dis.readUTF(); //阻塞式方法
System.out.println(str);
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();
}
}
}
}
}