I created a simple chat server that writes to all clients that is connected (I posted just the core code for simplicity)
public class server extends Thread {
private Socket clientSocket;
private static ArrayList<Socket> sockets = new ArrayList<Socket>();
public server(Socket clientSocket) {
this.clientSocket = clientSocket;
sockets.add(clientSocket);
}
public void run() {
while (true) {
try {
for(Socket s: sockets) {
//write something
//the for loop will send it to every socket in the array
}
} catch (Exception e) {
//catch it
}
}
}
}
Now I want to be more specific in what client I want to send the message to, just like how a real-world chat application will have different chat rooms.
So if Client1 connects to the server, he will want to start a chat group named "Apple". And then when Client2 and Client3 connects, they can choose to join the group "Apple". Simultaneously, Client 4 will connect to the server and create another chat group called "Banana" where other clients can join in and talk there.
My understanding is that I need to somehow identify each client that the server accepts (I have no idea how to implement this). Then do I somehow put them all into their own array based on their group chat name?
I've been searching for the past week sample codes that allow more than 1 group chat simultaneously but everything I've seen just caters towards 1 only.