服务端代码:
// 负责处理每个线程通信的线程类public class ServerThread implements Runnable{// 定义当前线程所处理的SocketSocket s = null;// 该线程所处理的Socket所对应的输入流BufferedReader br = null;public ServerThread(Socket s)throws IOException{this.s = s;// 初始化该Socket对应的输入流br = new BufferedReader(new InputStreamReader(s.getInputStream() , "utf-8")); //②}public void run(){try{String content = null;// 采用循环不断从Socket中读取客户端发送过来的数据while ((content = readFromClient()) != null){// 遍历socketList中的每个Socket,// 将读到的内容向每个Socket发送一次for (Socket s : MyServer.socketList){OutputStream os = s.getOutputStream();os.write((content + "\n").getBytes("utf-8"));}}}catch (IOException e){e.printStackTrace();}}// 定义读取客户端数据的方法private String readFromClient(){try{return br.readLine();}// 如果捕捉到异常,表明该Socket对应的客户端已经关闭catch (IOException e){// 删除该Socket。MyServer.socketList.remove(s); //①}return null;}}// 负责处理每个线程通信的线程类public class