import java.io.*; import java.net.*; import java.util.Vector; public class Server { ServerSocket ss; Vector clients = new Vector(); //创建一个容器 public Server(){ try { ss = new ServerSocket(6666); //创建一个服务器Socket System.out.println("服务器成功启动端口"); } catch (IOException e1) { System.out.println("端口已被占用"); } while (true) { Socket s; try { s = ss.accept(); //创建一个Socket,等待客户端接入 System.out.println("连接成功"); ClientThread client = new ClientThread(s);//创建一个ClientThread clients.add(client); client.start(); //并启用 } catch (IOException e) { System.out.println("客户连接失败"); } } } public static void main(String[] args) { new Server(); } class ClientThread extends Thread{ //写一个ClientThread继承Thread类 Socket s; DataInputStream dis; DataOutputStream dos; boolean connected; public ClientThread(Socket ts){ this.s = ts; try { dis = new DataInputStream(s.getInputStream());//用Socket接收输入流,放入DIS管子 dos = new DataOutputStream(s.getOutputStream()); //输出流 connected = true; //标记连接成功 } catch (Exception e) { System.out.println("连接输入流失败 handle exception"); } } public void sendMsg(String msg){ try { dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } public void run(){ while(connected){ //如果连接,就输出接收到的消息 try { // System.out.println(dis.readUTF()); String msg = dis.readUTF(); for(int i=0;i<clients.size();i++){ //发送给每一个客户端 ClientThread client = (ClientThread)clients.elementAt(i); client.sendMsg(msg); } } catch (Exception e) { connected = false; try { dis.close(); //关闭管子 } catch (IOException e2) { dis = null; } try { s.close(); //关闭SOCKET } catch (IOException e1) { s = null; } } } } } }