Tuesday, December 4, 2012

Limiting Simultaneous Web App Connections

Ever wanted to limit the number of users that could connect to your site from the same IP address? It's easy to do from the Session class.

1. Create a Shared Property on the Session class: Clients as Dictionary

2. Add a page to your app telling the user that there are too many users connected from their IP address, named TooManyUsers.

3. At the top of the Session.Open event, add the following code:

if clients = nil then clients = new Dictionary
dim addr as string = self.RemoteAddress
clients.value(addr) = clients.Lookup(addr,0) + 1
if clients.Lookup(addr,0) > 2 then
end if

4. In Session.Close:
dim addr as string = self.RemoteAddress
clients.value(addr) = max(0,clients.Lookup(addr,0) - 1)

Now, whenever a new session is created, it will increment the connection count for the IP address it is connecting from. If the number ever goes above 2, the user will be redirected to the TooManyUsers page. 

If you want to be really creative, put a WebTimer on the TooManyUsers page:

Period = 5000 (5 seconds)
Mode = 1 - Single

In the Timer1.Action event, set the code to something like:


This will not only show the user the error, but then after a short period of time, it will redirect them to another page of your choice, freeing up the server connection for another user.


Rick said...

Well... Nowadays IPs aren't very useful for consistency of the number of the connected clients, as a dozen pleople can be using the same IP behind a NAT-Firewall. There must be some kind of handshake and get some unique Id from that client, so 3 people behind a NAT have 1 IP and 3 GUIDs so they are 3 people and not mistaken as only one.

Greg O'Lone said...

That's true, but when I wrote this, I was thinking of a case where you might want to keep the number of connections from a single company below a certain number.