Skip to content

Commit

Permalink
net: add drop event for net server
Browse files Browse the repository at this point in the history
  • Loading branch information
theanarkh committed Jun 30, 2022
1 parent 42ad967 commit bbe1180
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
20 changes: 20 additions & 0 deletions doc/api/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,26 @@ added: v0.1.90

Emitted when the server has been bound after calling [`server.listen()`][].

### Event: `'drop'`

<!-- YAML
added: REPLACEME
-->

When the number of connections reaches the threshold of `server.maxConnections`,
the server will drop new connections and emit `'drop'` event instead. If it is a
TCP server, the arguments is as follow, otherwise return `undefined`.

```json
{
"localAddress": "::ffff:127.0.0.1",
"localPort": 61054,
"remoteAddress": "::ffff:127.0.0.1",
"remotePort": 61060,
"remoteFamily": "IPv6"
}
```

### `server.address()`

<!-- YAML
Expand Down
19 changes: 19 additions & 0 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,25 @@ function onconnection(err, clientHandle) {
}

if (self.maxConnections && self._connections >= self.maxConnections) {
if (clientHandle.getsockname || clientHandle.getpeername) {
const data = {};
if (clientHandle.getsockname) {
const localInfo = {};
clientHandle.getsockname(localInfo);
data.localAddress = localInfo.address;
data.localPort = localInfo.port;
}
if (clientHandle.getpeername) {
const remoteInfo = {};
clientHandle.getpeername(remoteInfo);
data.remoteAddress = remoteInfo.address;
data.remotePort = remoteInfo.port;
data.remoteFamily = remoteInfo.family;
}
self.emit('drop', data);
} else {
self.emit('drop');
}
clientHandle.close();
return;
}
Expand Down
26 changes: 26 additions & 0 deletions test/parallel/test-net-server-drop-connections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');

let firstSocket;
const server = net.createServer(common.mustCall((socket) => {
firstSocket = socket;
}));

server.maxConnections = 1;

server.on('drop', common.mustCall((data) => {
assert.strictEqual(!!data.localAddress, true);
assert.strictEqual(!!data.localPort, true);
assert.strictEqual(!!data.remoteAddress, true);
assert.strictEqual(!!data.remotePort, true);
assert.strictEqual(!!data.remoteFamily, true);
firstSocket.destroy();
server.close();
}));

server.listen(0, () => {
net.createConnection(server.address().port);
net.createConnection(server.address().port);
});

0 comments on commit bbe1180

Please sign in to comment.