Adding callback parameter to Socket's setTimeout method.
authorAli Farhadi <a.farhadi@gmail.com>
Wed, 26 Jan 2011 08:06:22 +0000 (11:36 +0330)
committerRyan Dahl <ry@tinyclouds.org>
Wed, 26 Jan 2011 20:13:03 +0000 (12:13 -0800)
doc/api/net.markdown
lib/net.js
test/simple/test-net-socket-timeout.js [new file with mode: 0644]

index 1789560..dab1df7 100644 (file)
@@ -226,7 +226,7 @@ Useful to throttle back an upload.
 
 Resumes reading after a call to `pause()`.
 
-#### socket.setTimeout(timeout)
+#### socket.setTimeout(timeout, [callback])
 
 Sets the socket to timeout after `timeout` milliseconds of inactivity on
 the socket. By default `net.Socket` do not have a timeout.
@@ -237,6 +237,8 @@ or `destroy()` the socket.
 
 If `timeout` is 0, then the existing idle timeout is disabled.
 
+The optional `callback` parameter will be added as a one time listener for the `'timeout'` event.
+
 #### socket.setNoDelay(noDelay=true)
 
 Disables the Nagle algorithm. By default TCP connections use the Nagle
index 9596725..5953c19 100644 (file)
@@ -690,10 +690,13 @@ Socket.prototype.setKeepAlive = function(enable, time) {
   }
 };
 
-Socket.prototype.setTimeout = function(msecs) {
+Socket.prototype.setTimeout = function(msecs, callback) {
   if (msecs > 0) {
     timers.enroll(this, msecs);
     if (this.fd) { timers.active(this); }
+    if (callback) {
+      this.once('timeout', callback);
+    }
   } else if (msecs === 0) {
     timers.unenroll(this);
   }
diff --git a/test/simple/test-net-socket-timeout.js b/test/simple/test-net-socket-timeout.js
new file mode 100644 (file)
index 0000000..c4d84fa
--- /dev/null
@@ -0,0 +1,23 @@
+var common = require('../common');
+var net = require('net');
+var assert = require('assert');
+
+var timedout = false;
+
+var server = net.Server();
+server.listen(common.PORT, function() {
+  var socket = net.createConnection(common.PORT);
+  socket.setTimeout(100, function() {
+    timedout = true;
+    socket.destroy();
+    server.close();
+    clearTimeout(timer);
+  });
+  var timer = setTimeout(function() {
+    process.exit(1);
+  }, 200);
+});
+
+process.on('exit', function() {
+  assert.ok(timedout);
+});