I am trying to make multi-thread server which should be able to communicate with many clients. I have ServerSocket
running in separate Thread, accepting all connections and packs all incoming Sockets in one synchronized ArrayList
. This works fine and I am receiving the messages from all the users. The problem is to send the messages.
I am trying with one static method sendMessage()
from separate class, which is called once send button is hit and the method iterates through all Sockets in my ArrayList
clientSockets
and sends the message but nothing comes to the clients:
public static void sendMessage(){
String messageOut;
messageOut = Graphics.writeMessage.getText(); //getting text from TextArea
Graphics.writeMessage.setText(""); //clearing TextArea
stateChanged("Message sent: ".concat(messageOut)); //changing state in another state TextArea
clientSockets.stream().forEach((Socket socket) -> {
//if (socket.isConnected() == true){
try{
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(messageOut);
out.flush();
} catch (IOException ex) {
Logger.getLogger(Pomocna.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
Here is a Thread which is called when a new client connects:
public class ClientThread extends Thread{
public Socket socket;
BufferedReader in;
PrintWriter out;
public ClientThread(Socket socket) throws IOException{
this.socket = socket;
Status.stausChanged("New client connected..."); //status TextArea
}
@Override
public void run () {
try{
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String msg ;
try {
msg = in.readLine();
Graphic.enterIP.setText(socket.getInetAddress().getHostAddress()); //show IP in separate window
//recieving message
while(msg!=null){
msg = in.readLine();
Status.stausChanged("Client ".concat(socket.getInetAddress().getHostAddress().concat(": ").concat(msg)));
}
out.close();
socket.close();
} catch (IOException e) {
}
}
catch(IOException exc){System.out.println("An error occured: " + exc.getMessage());}
}
}
I would appreciate if someone could give me an idea why this is not working and how to improve it. Also, I am not quite clear if static methods are good for doing such things. Thanks a lot in advance, hope I have managed to formulate the question in a clear way.