My program encounters an error during execution because the elements of arrlist from NewServer doesn't get copied to MyConnection. What should I do?
MyConnection is responsible for the sending and getting of the message and for the distribution of messages to all the clients.
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;
}
}
Here's the 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);
}
}