views:

351

answers:

3

My webpage loads a background flash which will connect to the server using socket. If a user open multiple windows/tabs of my website, the server will get multiple socket connections. Any idea of how to make sure that only one socket is connected from the same user and same browser?

I am thinking of using Javascript to monitor the window close event, if a window that was connected to the server is closed, one of the other windows will try to connect to the server. But I can't find a way to listen to that event.

I was thinking of Flash's LocalConnection too, but can't find a way to assign unique connection names and let other Flashes know.

A: 

The event you are looking for is called unload. Assuming you are using window.open to launch the window you might be able to do this:-

var win = window.open(url)
if (win.attachEvent)
    win.attachEvent("onunload", function() { // stuff when window closes });
else
    win.addEventListener("unload", function() { // stuff when window closes }, true);

However from bitter experience relying on unload events can be somewhat unreliable.

Edit

If the user opens these windows by their own means then the answer is a simple no, this can't be done.

AnthonyWJones
thanks, but what if the user opens other windows/tabs by themselves, we can't know what they have opened.
fxam
A: 

You can only control the windows you open yourself. There's no client-side way of controlling the other windows/tabs (and no server-side way to distinguish between them either).

Alan
+1  A: 

You might be able to do it from within Flash by using LocalConnection.

When a movie loads, try sending a test message to some LocalConnection ID. If that fails then the connection isn't open, in which case you open it to listen for commands, and you connect to the server via the socket.

If it succeeds then there's already a SWF running that's connected to the server. You can send any server requests that SWF gets over the LocalConnection to the one that's connected to the server.

If you need to get responses back then you may need to have the other SWFs open local connections of their own (random ID) and register them with the SWF that's connected to the server.

When the connected SWF gets shut down (window closed) all sends to that LocalConnection should fail. In which case your other SWFs would start getting errors. One of them would have to open that connection and become the "main" SWF (first one to successfully open the connection).

The lifecycle would be a bit weird, and there are probably a lot of corner cases you'd need to handle to make sure it stays robust, but it's an option. However, I've noticed that LocalConnection can become unreliable as the number of connections increases, so you'd probably be better off finding a different solution.

Herms
This should be feasible. Thanks !
fxam