I need to reuse socket for two connect calls made using http.request. I tried passing custom agent limiting number of sockets but the first socket is removed before the 2nd connect call is made by code: https://github.com/nodejs/node/blob/master/lib/_http_client.js#L438
mock code:
var options = { method: 'CONNECT', agent: new http.Agent({ keepAlive: true, maxSockets: 1 }) }; var request = this.httpModule.request(options); request.on('connect', (res, sock, head) => { console.log(sock.address()); // some processing... var request2 = this.httpModule.request(options); request2.on('connect', (res, sock, head) => { console.log(sock.address()); }); request2.end(); }); request.end();
Is there some way by which I can reuse the same socket for two connect calls?
1 Answers
Answers 1
The two unique sockets are required for this form of communication.
Each socket in this case represents a connection between a client and a server. There is no such socket that represents n
clients and one server, so to speak. They also don't act like "threads" here, where one socket can perform work for many clients.
By setting the max sockets to 1, you've requested that only 1 client connection be active at any time. When you try to connect that second client, it kills the first one because the max is reached and we need room for a new connection!
If you want to recycle sockets -- For example, a client connects, refreshes the page after an hour, and the same client triggers another connection -- There's probably not a way to do it this high in the technology stack, and it would be far more complicated and unnecessary than destroying the old socket to make way for a new one anyway. If you don't understand why you would or wouldn't need to do this, you don't need to do it.
If you want to send a message to many clients (and you wanted to accomplish it "under one socket" in your question), consider using the broadcast
and emit
methods.
0 comments:
Post a Comment