dgram: socket add asyncDispose

PR-URL: https://github.com/nodejs/node/pull/48717
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
This commit is contained in:
atlowChemi
2023-07-10 00:21:58 +03:00
committed by Node.js GitHub Bot
parent ccdfb37438
commit 17f6b8c49c
3 changed files with 41 additions and 1 deletions

View File

@@ -372,6 +372,17 @@ added: v0.1.99
Close the underlying socket and stop listening for data on it. If a callback is
provided, it is added as a listener for the [`'close'`][] event.
### `socket[Symbol.asyncDispose]()`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
Calls [`socket.close()`][] and returns a promise that fulfills when the
socket has closed.
### `socket.connect(port[, address][, callback])`
<!-- YAML
@@ -992,4 +1003,5 @@ and `udp6` sockets). The bound address and port can be retrieved using
[`socket.address().address`]: #socketaddress
[`socket.address().port`]: #socketaddress
[`socket.bind()`]: #socketbindport-address-callback
[`socket.close()`]: #socketclosecallback
[byte length]: buffer.md#static-method-bufferbytelengthstring-encoding

View File

@@ -30,6 +30,7 @@ const {
ObjectDefineProperty,
ObjectSetPrototypeOf,
ReflectApply,
SymbolAsyncDispose,
SymbolDispose,
} = primordials;
@@ -59,7 +60,7 @@ const {
validatePort,
} = require('internal/validators');
const { Buffer } = require('buffer');
const { deprecate, guessHandleType } = require('internal/util');
const { deprecate, guessHandleType, promisify } = require('internal/util');
const { isArrayBufferView } = require('internal/util/types');
const EventEmitter = require('events');
const {
@@ -752,6 +753,13 @@ Socket.prototype.close = function(callback) {
return this;
};
Socket.prototype[SymbolAsyncDispose] = async function() {
if (!this[kStateSymbol].handle) {
return;
}
return FunctionPrototypeCall(promisify(this.close), this);
};
function socketCloseNT(self) {
self.emit('close');

View File

@@ -0,0 +1,20 @@
import * as common from '../common/index.mjs';
import assert from 'node:assert';
import dgram from 'node:dgram';
import { describe, it } from 'node:test';
describe('dgram.Socket[Symbol.asyncDispose]()', () => {
it('should close the socket', async () => {
const server = dgram.createSocket({ type: 'udp4' });
server.on('close', common.mustCall());
await server[Symbol.asyncDispose]().then(common.mustCall());
assert.throws(() => server.address(), { code: 'ERR_SOCKET_DGRAM_NOT_RUNNING' });
});
it('should resolve even if the socket is already closed', async () => {
const server = dgram.createSocket({ type: 'udp4' });
await server[Symbol.asyncDispose]().then(common.mustCall());
await server[Symbol.asyncDispose]().then(common.mustCall(), common.mustNotCall());
});
});