I’m having some problems removing clients from a channellist.
This is the code i have at the moment:
Serverside:
private Hashtable<String, ArrayList<String>> channels = new Hashtable<String, ArrayList<String>>();
public synchronized void logMeOut(String username) throws RemoteException {
for(Client c : clients){
if(c.findName().equals(username)){
clients.remove(c);
disconnectAllChans(username);
System.out.println(username + " removed from clientlist.");
}
}
updateJListForOnlineUsers(); //Callback for other clients to update the userlist.
}
public void disconnectAllChans(String username) throws RemoteException{
for(Enumeration e = channels.elements(); e.hasMoreElements();){
if(channels.contains(username)){
channels.remove(username);
}
}
updateJListForUsersInChannel();
System.out.println("User " + username + " left all channel");
}
I have tried both if(channels.contains(username), and containsKey. None of them seems to do the work. When i leave the server, which runs the logout method, the client just hangs. I’m guessing its going on a foreverloop in that Enumeration loop.
EDIT: The client only hangs IF it has joined a channel. If the channellist for a user is empty, it quits right away.
Any ideas how the code should look?
**
Solution:
**
So yeah, i figured it out, but i wouldn’t have without you guys. Thanks
I just ran the disconnectmethod inside the disconnect all channels method which brainzzy posted. Heres the result:
@Override
public void disconnectChannel(String username, String channel) throws RemoteException{
if(isUserInChannelX(username, channel)){
channels.get(channel).remove(username);
String message = "User " + username + " left the channel.";
notifySelf(username, " You have left the channel " + channel);
notifyChannelSystem(channel, "SYSTEM", message);
updateJListForActiveChannels();
if(channels.get(channel).isEmpty()){
channels.remove(channel);
}
}
}
public void disconnectAllChans(String username) throws RemoteException{
for (String channel : channels.keySet()) {
ArrayList<String> members = channels.get(channel);
if (members.contains(username)) {
disconnectChannel(username, channel);
System.out.println("User " + username + " left channel " + channel);
}
}
updateJListForUsersInChannel();
}
I feel kinda stupid ^^ Thanks people!
Replace the for with a foreach loop, makes it harder to make infinite loop errors like you’ve got yourself into by not handling the enumerator correctly:
I think that’ll do what you want it to.