my server only needs to send message to all clients. This question has been asked numerous times and the solution is to create an arraylist and to send to all just iterate over it calling the required method
i took the server example found at link here
quoted below
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiThreadServer implements Runnable {
Socket csocket;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
PrintStream pstream = new PrintStream(csocket.getOutputStream());
for (int i = 100; i >= 0; i--) {
pstream.println(i + " bottles of beer on the wall");
}
pstream.close();
csocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
just i changed the code in run() to
boolean running = true;
public void run() {
while(running){
try {
InputStream inFromCli = csocket.getInputStream();
DataOutputStream out = new DataOutputStream(csocket.getOutputStream());
conns.add(out);
DataInputStream in = new DataInputStream(inFromCli);
String inMsg = in.readUTF();
String[] words= inMsg.split(" ");
if(".sendall".equals(words[0])){
for(DataOutputStream elem : conns){
elem.writeUTF("tgthrt");
elem.flush();
}
}
} catch (IOException e) {
running= false;
}
}
}
where conns is an arrayList defined thus :
ArrayList<DataOutputStream> conns = new ArrayList<>();
however, when i iterate, it does not send to all clients. How can i modify it?