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 27, 2022
1 parent 42ad967 commit 790c9d6
Show file tree
Hide file tree
Showing 3 changed files with 61 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 conenctions reached the threshold(`server.maxConnections`),
the server will drop the connection and emit drop event. If it is a TCP server,
the arguments is as follow.

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

### `server.address()`

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

if (self.maxConnections && self._connections >= self.maxConnections) {
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);
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 net = require('net');
const assert = require('assert');

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

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();
}, 1));

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

0 comments on commit 790c9d6

Please sign in to comment.