我的程序在执行期间遇到错误,因为NewServer的arrlist元素没有被复制到MyConnection。我该怎么办?
MyConnection负责发送和获取消息以及向所有客户端分发消息。
public class MyConnection extends Thread{
Socket s;
BufferedReader in;
PrintWriter out;
String reps, msg;
ArrayList<MyConnection> arrlist;
MyConnection(Socket s, ArrayList<MyConnection> arrlist){
this.arrlist = arrlist;
this.s = s;
try{
this.in= new BufferedReader(new InputStreamReader(s.getInputStream()));
this.out= new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
}catch(IOException e){
System.out.println("Something Bad Happened " + e);
}
}
boolean sendMessage(String msg){
try{
NewServer server = new NewServer();
server.sendtoAll(msg);
out.println(msg);
out.flush();
System.out.println(server.arrlist.size());
return true;
}catch (Exception e) {
System.out.println("S: Something bad happened :(");
e.printStackTrace();
return false;
}
}
String getMessage(){
try{
reps = in.readLine();
}catch (Exception e) {
System.out.println("S: Something bad happened :(");
e.printStackTrace();
}
return reps;
}
}
这里是NewServer
public class NewServer{
static ArrayList<MyConnection> arrlist = new ArrayList<MyConnection>();
static boolean push;
static Socket s;
public void sendtoAll(String message){
for(int i= arrlist.size(); i >= 0; i--){
MyConnection t3 = arrlist.get(i);
t3.sendMessage(message);
if(!t3.sendMessage(message)){
arrlist.remove(i);
System.out.println("Client disconnected");
}
}
}
public static void main(String args[]){
try{
System.out.println("S: Starting server...");
ServerSocket ssocket = new ServerSocket(8888);
System.out.println("S: Waiting for connections...");
while(true){
s = ssocket.accept();
System.out.println("SOMEONE CONNECTEDDDDD" + arrlist.size());
MyConnection t = new MyConnection(s,arrlist);
arrlist.add(t); //put my connection to arrlist
t.start();
}
}catch(Exception e) {
System.out.println("Soooomething Bad Happened " + e);
}
}
答案 0 :(得分:0)
您将无法编辑正在迭代的列表,您可以执行以下操作:
public void sendtoAll(String message){
ArrayList<MyConnection> tempArrlist = new ArrayList<MyConnection>()
for(int i= arrlist.size(); i >= 0; i--){
MyConnection t3 = arrlist.get(i);
t3.sendMessage(message);
if(t3.sendMessage(message)){
tempArrlist.add(arrlist.get(i));
} else {
System.out.println("Client disconnected");
}
}
arrlist = tempArrlist;
}