eBlogzilla

Monday, May 24, 2010

How to detect is a socket free or busy

Sometimes you need to perform very simple task. But unexpectedly this task can take much more time that you have expected at the start.

I've met this case when I was need to check if some socket is free or busy. I've spent some time on playing with core Mozilla interfaces like nsIServerSocket or nsISocketTransportService. But was not able to find right solution.

Finally, I've used not very traditional method to solve my problem. I've managed all work to Java classes:
function isPortAvailable(port) {
    try {
        var srv = new java.net.ServerSocket(port);
        srv.close();
        srv = null;
        return true;
    } catch (e) {
        return false;
    }
}

This solution has one limitation. You need to be ensure that Java in installed on user's machine. But in my case this limitation was not significant.