I'm trying to close a socket after a connection times out after 1000ms. I am able to set a timeout that gets triggered after a 1000ms but I can't seem to destroy the socket... any ideas?
var connection = http.createClient(80, 'localhost');
var request = connection.request('GET', '/somefile.xml', {'host':'localhost'});
var start = new Date().getTime();
request.socket.setTimeout(1000);
request.socket.addListener("timeout", function() {
request.socket.destroy();
sys.puts("socket timeout connection closed");
});
request.addListener("response", function(response) {
var responseBody = [];
response.setEncoding("utf8");
response.addListener("data", function(chunk) {
sys.puts(chunk);
responseBody.push(chunk);
});
response.addListener("end", function() {
});
});
request.end();
returns
socket timeout connection closed
node开发者_Python百科.js:29
if (!x) throw new Error(msg || "assertion error");
^
Error: assertion error
at node.js:29:17
at Timer.callback (net:152:20)
at node.js:204:9
There are two way. The problem is a bug.
upgrade node.js to gt 0.3.7 https://github.com/joyent/node/commit/2ec4cd552501b895c83c6871951c1a6256288c48
edit the code https://github.com/Hotelsnl/Socket.IO-node/blob/63624e5996b2719bb08f38a8af143c2019617da3/lib/socket.io/client.js
You might get better answers on the IRC channel #node.js
on freenode. But AFAIK node isn't quite designed for canceling something mid-way. Mostly people just leave it dangling since, in node.js, there's no blocking I/O anyway.
I agree though, that there should be a way to cancel something mid-way, but I don't think you should mess with the request's internal socket connection. That's why you have the http.ClientRequest
abstraction to manage the socket for you. The error could be because the timeout does works but that the request object weren't expecting the socket to already be closed.
Hope this helps.
精彩评论