I’m in a situation where I have a session which gets an ID assigned by it with a simple counter. Well, after a lot of connections the counter will be at 500, even though there might be only 2 people connected. What I want to do is have a counter which flags numbers as free so they are re-usable! I don’t have any idea how to tackle this though. I hope one of you might be able to help me out!
public void createSession(Socket gameClient)
{
uint sessionID = mSessionCounter++;
Session Session = new Session(sessionID, gameClient);
mSessions.Add(sessionID, Session);
CommandLine.WriteLine("Created session " + sessionID + " for " + Session.ipAddress, CommandLine.logType.sessionConnectionEvent);
Session.Start();
}
Just a quick idea of who you could do this. Although re-using may not be required in your case, it might still be something worth knowing how to do (plus having an answer to this question would be good).
If you need to check which session ID’s are in use at any time, then you need to be able to track them. For this I would suggest a simple
Listwould do fine, so lets start with something like:this should be globally accessible. To ensure this list is kept clean, in your function that checks for “stay alive” you can remove an item like so:
Next, you want to work out the first available session number using your list as an exceptions list. You can do this with Linq as follows:
Note: this bit of lovely Linq syntax for finding the first available number was inspired by this post (credit where it’s due, etc.)