Skip to content
Advertisement

Server doesn’t forward message to all in the chat

i am trying to create a simple chat app using java sockets, the server is threaded, when a client connects its socket is added to an ArrayList, so that i can send to all in that list.

the problem is when 3 clients are connected, the for loop that sends doesn’t work properly, for ex : client 0 sends to both 1 and 2 but client 2 doesn’t send to anyone 🙁

The server and the ClientHandler :

JavaScript

The client :

JavaScript

I think the problem is here :

JavaScript

Advertisement

Answer

The fix is straightforward: remove the break statement from the loop where you think the problem is.

This break statement causes the loop through all the ClientHandlers to stop as soon as it sends the message to one client. You don’t want this: you want this loop to keep going and send the message to all clients other than the one that wrote the message.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement