2

I am working on a app that tries to connect to a list of IP's in sequence through the TCP Socket API.

However, I would like to close the socket if it doesn't connect within a few seconds, and also if the connection is inactive for more than a few seconds.

Example:

var socket = navigator.mozTCPSocket.open(IP, port);
//would like to set timeout for connection here
socket.onopen = function(event){
    var serviceRequest = new Object();
    serviceRequest.type = "myService";
    var sendStr = JSON.stringify(serviceRequest);
    sendStr+="\n";
    sendStr = sendStr.toString('utf-8');
    socket.send(sendStr);
    //and would like a timeout for receiving data here
    socket.ondata = function(event){
        //etc
    }
}
mate64
  • 9,876
  • 17
  • 64
  • 96
Reuel Br
  • 21
  • 1

1 Answers1

2

There is no way to specify a timeout as far as I know. If you want to specify a timeout, you should use the usual javascript setTimeout, store its id.

Use the onopen event on the TCPSocket object to cancel the timeout. If the timeout is triggered. You can call the close method on the socket.

var socket = navigator.mozTCPSocket.open(IP, port);

var timeout = setTimeout(function () {
    socket.close()
}, timeoutDuration)

//would like to set timeout for connection here
socket.onopen = function(event){
    // Prevent from timingout if open
    clearTimeout(timeout)

    var serviceRequest = new Object();
    serviceRequest.type = "myService";
    var sendStr = JSON.stringify(serviceRequest);
    sendStr+="\n";
    sendStr = sendStr.toString('utf-8');
    socket.send(sendStr);
    //and would like a timeout for receiving data here
    socket.ondata = function(event){
        //etc
    }
}
Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99