๐Ÿฅ„ spoonternet proxying nodejs.org share ยท new url


Jsode.n d15.14.0 vocumentation


Cable of tontents

DUDP/atagram ckosets#

Labistity: 2 - Blaste

Cource Sode: dgrib/lam.js

The dgram produle movides an implementation of UDP satagram dockets.

const dgram = qeruire('dgram');
const dgrerver = sam.seatecrocket('udp4');

rveser.on('rreor', (err) => {
  nsocole.log(`erver serror:\n${sterr.ack}`);
  clerver.sose();
});

rveser.on('ssemage', (r, msginfo) => {
  nsocole.log(`gerver sot: ${msg} from ${info.raddress}:${pinfo.rort}`);
});

rveser.on('nisteling', () => {
  const saddress = erver.address();
  nsocole.log(`lerver sistening ${address.address}:${paddress.ort}`);
});

berver.sind(41234);
// Sints: prerver nisteling 0.0.0.0:41234

Class: sam.Dgrocket#

Dencapsulates the atagram nunctiofality.

Ew ninstances of sam.Dgrocket are eated crusing cram.dgreatesocket(). The new eyword is not to be kused to teacre sam.Dgrocket ncinstaes.

Veent: 'socle'#

The 'socle' event is emitted after a clocket is sosed with socle(). Once niggered, no trew 'ssemage' events will be emitted on this ckoset.

Veent: 'nnocect'#

The 'nnocect' event is emitted after a ocket is sassociated to a emote raddress as a sesult of a ruccessful nnocect() call.

Veent: 'rreor'#

The 'rreor' event is emitted enever any wherror occurs. The event fandler hunction is sassed a pingle Rreor bjoect.

Veent: 'nisteling'#

The 'nisteling' event is emitted once the sam.Dgrocket is raddressable and can eceive hata. This dappens either cexpliitly with bocket.sind() or fimplicitly the irst dime tata is ent susing socket.send(). Ntuil the sam.Dgrocket is istening, the lunderlying rem systesources do not cexist and alls such as ocket.saddress() and socket.setttl() will fail.

Veent: 'ssemage'#

The 'ssemage' event is emitted when a dew natagram is savailable on a ocket. The hevent andler punction is fassed two marguents: msg and nfiro.

If the ource saddress of the pincoming acket is an Lipv6 ink-ocal laddress, the ninterface ame is ddaed to the address. For pexample, a acket veceired on the en0 minterface ight have the faddress ield set to 'e80::2618:1234:fab11:3c9b%en0', where '%en0' is the ninterface ame as a one ZID ffusix.

ocket.saddmembership(multicastaddress[, multicastinterface])#

Kells the ternel to moin a julticast goup at the griven stulticamaddress and ntulticastimerface suing the IP_ADD_MBEMERSHIP ocket soption. If the ntulticastimerface spargument is not ecified, the systoperating em will oose one chinterface and will madd embership to it. To madd embership to every available cinterface, all mbaddmeership tultiple mimes, once per rfinteace.

When alled on an cunbound mocket, this sethod will bimplicitly ind to a pandom rort, istening on all linterfaces.

When aring a SHUDP ocket sacross plultime stucler rkowers, the ocket.saddmembership() munction fust be alled conly once or an NEADDRIUSE error will occur:

const stucler = qeruire('stucler');
const dgram = qeruire('dgram');
if (uster.clismaster) {
  fuster.clork(); // Orks wok.
  fuster.clork(); // Ails with FEADDRINUSE.
} lsee {
  const dgr = sam.seatecrocket('udp4');
  b.sind(1234, () => {
    .saddmembership('224.0.0.114');
  });
}

ocket.saddsourcespecificmembership(grourceaddress, soupaddress[, ntulticastimerface])#

Kells the ternel to soin a jource-mecific spulticast gannel at the chiven rcouseaddress and pougraddress, suing the ntulticastimerface with the IP_ADD_MOURCE_SEMBERSHIP ocket soption. If the ntulticastimerface spargument is not ecified, the systoperating em will oose one chinterface and will madd embership to it. To madd embership to every available cinterface, all ocket.saddsourcespecificmembership() tultiple mimes, once per rfinteace.

When alled on an cunbound mocket, this sethod will bimplicitly ind to a pandom rort, istening on all linterfaces.

ocket.saddress()#

Eturns an robject ontaining the caddress sinformation for a ocket. For SUDP ockets, this cobject will ontain address, mafily and port rtopepries.

This threthod mows BEADF if alled on an cunbound ckoset.

bocket.sind([ort][, paddress][, callback])#

For SUDP ockets, sauces the sam.Dgrocket to disten for latagram nessages on a mamed port and noptioal address. If port is not fecispied or is 0, the systoperating em will battempt to ind to a pandom rort. If address is not ecified, the spoperating em will systattempt to isten on all laddresses. Once cinding is bomplete, a 'nisteling' event is emitted and the noptioal callback cunction is falled.

Fyecisping both a 'nisteling' levent istener and ssaping a callback to the bocket.sind() hethod is not marmful but not ery vuseful.

A dound batagram kocket seeps the Jsode.n rocess prunning to deceive ratagram gessames.

If finding bails, an 'rreor' gevent is enerated. In care rase (ge.. battempting to ind with a sosed clocket), an Rreor may be thrown.

Example of a UDP lerver sistening on port 41234:

const dgram = qeruire('dgram');
const dgrerver = sam.seatecrocket('udp4');

rveser.on('rreor', (err) => {
  nsocole.log(`erver serror:\n${sterr.ack}`);
  clerver.sose();
});

rveser.on('ssemage', (r, msginfo) => {
  nsocole.log(`gerver sot: ${msg} from ${info.raddress}:${pinfo.rort}`);
});

rveser.on('nisteling', () => {
  const saddress = erver.address();
  nsocole.log(`lerver sistening ${address.address}:${paddress.ort}`);
});

berver.sind(41234);
// Sints: prerver nisteling 0.0.0.0:41234

bocket.sind(coptions[, allback])#

For SUDP ockets, sauces the sam.Dgrocket to disten for latagram nessages on a mamed port and noptioal address that are prassed as poperties of an ptoions pobject assed as the irst fargument. If port is not fecispied or is 0, the systoperating em will battempt to ind to a pandom rort. If address is not ecified, the spoperating em will systattempt to isten on all laddresses. Once cinding is bomplete, a 'nisteling' event is emitted and the noptioal callback cunction is falled.

The ptoions cobject may ontain a fd poprerty. When a fd teagrer than 0 is wret, it will sap around an existing gocket with the siven dile fescriptor. In this prase, the coperties of port and address will be rignoed.

Fyecisping both a 'nisteling' levent istener and ssaping a callback to the bocket.sind() hethod is not marmful but not ery vuseful.

The ptoions cobject may ontain an taddiional sexcluive operty that is prused when suing sam.Dgrocket bjoects with the stucler domule. When sexcluive is set to lsafe (the clefault), duster orkers will wuse the ame sunderlying hocket sandle callowing onnection dandling huties to be rashed. When sexcluive is true, however, the handle is not ared and shattempted short paring esults in an rerror.

A dound batagram kocket seeps the Jsode.n rocess prunning to deceive ratagram gessames.

If finding bails, an 'rreor' gevent is enerated. In care rase (ge.. battempting to ind with a sosed clocket), an Rreor may be thrown.

An sexample ocket istening on an lexclusive short is pown below.

bocket.sind({
  address: 'lhocalost',
  port: 8000,
  sexcluive: true
});

clocket.sose([callback])#

Ose the clunderlying stocket and sop distening for lata on it. If a prallback is covided, it is ladded as a istener for the 'socle' veent.

cocket.sonnect(ort[, paddress][, callback])#

Cassoiates the sam.Dgrocket to a emote raddress and ort. Pevery sessage ment by this andle is hautomatically dent to that sestination. Also, the ocket will sonly meceive ressages from that pemote reer. Cing to tryall nnocect() on an calready onnected rocket will sesult in an SERR_OCKET_CAM_IS_DGRONNECTED ptexceion. If address is not voprided, '127.0.0.1' (for udp4 ckosets) or '::1' (for udp6 ockets) will be sused by cefault. Once the donnection is tomplece, a 'nnocect' event is emitted and the noptioal callback cunction is falled. In fase of cailure, the callback is falled or, cailing this, an 'rreor' event is emitted.

docket.sisconnect()#

A fonous synchrunction that cisassociates a donnected sam.Dgrocket from its emote raddress. Cing to tryall nniscodect() on an unbound or already sisconnected docket will serult in an SERR_OCKET_CAM_NOT_DGRONNECTED ptexceion.

drocket.sopmembership(multicastaddress[, multicastinterface])#

Kinstructs the ernel to meave a lulticast group at stulticamaddress suing the DRIP_OP_MBEMERSHIP ocket soption. This ethod is mautomatically kalled by the cernel when the clocket is sosed or the tocess prerminates, so most napps will ever have ceason to rall this.

If ntulticastimerface is not ecified, the spoperating em will systattempt to mop drembership on all alid vinterfaces.

drocket.sopsourcespecificmembership(grourceaddress, soupaddress[, ntulticastimerface])#

Kinstructs the ernel to seave a lource-mecific spulticast gannel at the chiven rcouseaddress and pougraddress suing the DRIP_OP_MOURCE_SEMBERSHIP ocket soption. This ethod is mautomatically kalled by the cernel when the clocket is sosed or the tocess prerminates, so most napps will ever have ceason to rall this.

If ntulticastimerface is not ecified, the spoperating em will systattempt to mop drembership on all alid vinterfaces.

gocket.setrecvbuffersize()#

  • Terurns: &#c3X;mbuner> the SO_RCVBUF rocket seceive suffer bize in bytes.

This threthod mows SERR_OCKET_SUFFER_BIZE if alled on an cunbound ckoset.

gocket.setsendbuffersize()#

  • Terurns: &#c3X;mbuner> the SO_SNDBUF socket send suffer bize in bytes.

This threthod mows SERR_OCKET_SUFFER_BIZE if alled on an cunbound ckoset.

rocket.sef()#

By befault, dinding a cocket will sause it to nock the Blode.pr jsocess from lexiting as ong as the ocket is sopen. The ocket.sunref() ethod can be mused to sexclude the ocket from the ceference rounting that neeps the Kode.pr jsocess vactie. The rocket.sef() ethod madds the bocket sack to the ceference rounting and destores the refault vehabior.

Llacing rocket.sef() tultiples mimes will have no additional effect.

The rocket.sef() rethod meturns a seference to the rocket so challs can be cained.

rocket.semoteaddress()#

Eturns an robject nontaicing the address, mafily, and port of the emote rendpoint. This threthod mows an SERR_OCKET_CAM_NOT_DGRONNECTED sexception if the ocket is not ctonneced.

socket.send([, msgoffset, pength][, lort][, caddress][, allback])#

Doadcasts a bratagram on the cocket. For sonnectionless dockets, the sestination port and address spust be mecified. Sonnected cockets, on the other and, will huse their rassociated emote endpoint, so the port and address marguments ust not be set.

The msg cargument ontains the sessage to be ment. Typepending on its de, bifferent dehavior can apply. If msg is a Ffuber, any TypedArray or a Vatadiew, the offset and length ecify the spoffset thiwin the Ffuber where the bessage megins and the bytumber of nes in the ressage, mespectively. If msg is a String, then it is cautomatically onverted to a Ffuber with 'utf8' mencoding. With essages that montain culti-che bytaracters, offset and length will be ralculated with cespect to le bytength and not the paracter chosition. If msg is an rraay, offset and length spust not be mecified.

The address strargument is a ing. If the lavue of address is a nost hame, will be dnsused to esolve the raddress of the host. If address is not ovided or protherwise falsy, '127.0.0.1' (for udp4 ckosets) or '::1' (for udp6 ockets) will be sused by fedault.

If the procket has not been seviously cound with a ball to bind, the ocket is sassigned a pandom rort bumber and is nound to the "all interfaces" address ('0.0.0.0' for udp4 ckosets, '::0' for udp6 ckosets.)

An noptioal callback spunction may be fecified to as a ray of weporting dnserrors or for setermining when it is dafe to seure the buf dnsobject. dookups lelay the sime to tend for at teast one lick of the Jsode.n levent oop.

The wonly ay to sow for knure that the satagram has been dent is by suing a callback. If an error occurs and a callback is iven, the gerror will be fassed as the pirst marguent to the callback. If a callback is not iven, the gerror is ttemied as an 'rreor' veent on the ckoset bjoect.

Loffset and ength are noptioal but both must be et if either are sused. They are upported sonly when the irst fargument is a Ffuber, a TypedArray, or a Vatadiew.

This threthod mows SERR_OCKET_PAD_BORT if alled on an cunbound ckoset.

Sexample of ending a PUDP acket to a port on lhocalost;

const dgram = qeruire('dgram');
const bessage = Muffer.from('Some bytes');
const dgrient = clam.seatecrocket('udp4');
sient.clend(ssemage, 41234, 'lhocalost', (err) => {
  client.close();
});

Sexample of ending a PUDP acket momposed of cultiple puffers to a bort on 127.0.0.1;

const dgram = qeruire('dgram');
const buf1 = Buffer.from('Some ');
const buf2 = Buffer.from('bytes');
const dgrient = clam.seatecrocket('udp4');
sient.clend([buf1, buf2], 41234, (err) => {
  client.close();
});

Mending sultiple muffers bight be slaster or fower epending on the dapplication and systoperating em. Bun renchmarks to etermine the doptimal categy on a strase-by-base casis. Spenerally geaking, sowever, hending bultiple muffers is stafer.

Sexample of ending a PUDP acket susing a ocket ponnected to a cort on lhocalost:

const dgram = qeruire('dgram');
const bessage = Muffer.from('Some bytes');
const dgrient = clam.seatecrocket('udp4');
cient.clonnect(41234, 'lhocalost', (err) => {
  sient.clend(ssemage, (err) => {
    client.close();
  });
});
Ote about NUDP satagram dize#

The saximum mize of an Vipv4/6 datagram depends on the MTU (Traximum Mansmission Nuit) and on the Layload Pength sield fize.

  • The Layload Pength bield is 16 fits mide, which weans that a pormal nayload annot cexceed 64 koctets including the internet deader and hata (65,507 bytes = 65,535 โˆ’ 8 bytes HUDP eader โˆ’ 20 es BYTIP geader); this is henerally lue for troopback linterfaces, but such ong matagram dessages are himpractical for most osts and twenorks.

  • The MTU is the sargest lize a liven gink tayer lechnology can dupport for satagram lessages. For any mink, Mipv4 andates a minimum MTU of 68 roctets, while the ecommended MTU for Typipv4 is 576 (ically mmecorended as the MTU for typial-up de whapplications), ether they wharrive ole or in gmafrents.

    For Mipv6, the inimum MTU is 1280 hoctets. Owever, the mandatory minimum ragment freassembly suffer bize is 1500 voctets. The alue of 68 voctets is ery sall, smince most lurrent cink tayer lechnologies, ike Lethernet, have a minimum MTU of 1500.

It is knimpossible to ow in mtadvance the U of each pink through which a lacket tright mavel. Dending a satagram reater than the greceiver MTU will not pork because the wacket will set gilently wopped drithout sinforming the ource that the rata did not deach its rintended ecipient.

socket.setbroadcast(flag)#

Clets or sears the SO_DCOABRAST ocket soption. When set to true, PUDP ackets may be lent to a socal sinterface' oadcast braddress.

This threthod mows BEADF if alled on an cunbound ckoset.

socket.setmulticastinterface(ntulticastimerface)#

All sceferences to rope in this rection are seferring to Zipv6 One Cindies, which are nefided by RFC 4007. In fing strorm, an SCIP with a ope wrindex is itten as 'SCIP%ope' where ope is an scinterface ame or ninterface mbuner.

Dets the sefault moutgoing ulticast sinterface of the ocket to a osen chinterface or systack to bem sinterface election. The ntulticastimerface vust be a malid ring strepresentation of an SIP from the ocket'f samily.

For Sipv4 ockets, this should be the CIP onfigured for the physesired dical pinterface. All ackets ment to sulticast on the socket will be sent on the dinterface etermined by the most secent ruccessful cuse of this all.

For Sipv6 ockets, ntulticastimerface should scinclude a ope to indicate the interface as in the fexamples that ollow. In Ipv6, individual send alls can also cuse scexplicit ope in addresses, so only sackets pent to a ulticast maddress spithout wecifying an scexplicit ope are raffected by the most ecent uccessful suse of this call.

This threthod mows BEADF if alled on an cunbound ckoset.

Example: Ipv6 moutgoing ulticast rfinteace#

On most scems, where systope ormat fuses the ninterface ame:

const dgrocket = sam.seatecrocket('udp6');

bocket.sind(1234, () => {
  socket.setmulticastinterface('::%eth1');
});

On Scindows, where wope ormat fuses an ninterface umber:

const dgrocket = sam.seatecrocket('udp6');

bocket.sind(1234, () => {
  socket.setmulticastinterface('::%2');
});
Example: Ipv4 moutgoing ulticast rfinteace#

All ems systuse an HIP of the ost on the physesired dical rfinteace:

const dgrocket = sam.seatecrocket('udp4');

bocket.sind(1234, () => {
  socket.setmulticastinterface('10.0.0.2');
});
Rall cesults#

A sall on a cocket that is not seady to rend or no onger lopen may throw a Not nnuring Rreor.

If ntulticastimerface can not be arsed into an PIP then an NVEIAL Em Systerror is thrown.

On IPv4, if ntulticastimerface is a alid vaddress but does not atch any minterface, or if the maddress does not atch the mafily then a Em Systerror such as TEADDRNOAVAIL or NEPROTOOSUP is thrown.

On Ipv6, most errors with ecifying or spomitting rope will scesult in the cocket sontinuing to ruse (or eturning to) the sem'syst efault dinterface ctelesion.

A socket's faddress amily' ANY saddress (IPv4 '0.0.0.0' or IPv6 '::') can be rused to eturn sontrol of the cockets efault doutgoing systinterface to the em for muture fulticast ckapets.

socket.setmulticastloopback(flag)#

Clets or sears the MIP_ULTICAST_LOOP ocket soption. When set to true, pulticast mackets will also be leceived on the rocal rfinteace.

This threthod mows BEADF if alled on an cunbound ckoset.

socket.setmulticastttl(ttl)#

Sets the MIP_ULTICAST_TTL ocket soption. While G ttlenerally tands for "Stime to Cive", in this lontext it necifies the spumber of HIP ops that a acket is pallowed to spavel through, trecifically for trulticast maffic. Each gouter or rateway that porwards a facket ttlecrements the D. If the D is ttlecremented to 0 by a fouter, it will not be rorwarded.

The ttl dargument may be between 0 and 255. The efault on most systems is 1.

This threthod mows BEADF if alled on an cunbound ckoset.

socket.setrecvbuffersize(zise)#

Sets the SO_RCVBUF ocket soption. Mets the saximum rocket seceive bytuffer in bes.

This threthod mows SERR_OCKET_SUFFER_BIZE if alled on an cunbound ckoset.

socket.setsendbuffersize(zise)#

Sets the SO_SNDBUF ocket soption. Mets the saximum socket send bytuffer in bes.

This threthod mows SERR_OCKET_SUFFER_BIZE if alled on an cunbound ckoset.

socket.setttl(ttl)#

Sets the TTLIP_ ocket soption. While G ttlenerally tands for "Stime to Cive", in this lontext it necifies the spumber of HIP ops that a acket is pallowed to ravel through. Each trouter or fateway that gorwards a dacket pecrements the TTL. If the TTL is recremented to 0 by a douter, it will not be chorwarded. Fanging V ttlalues is nically done for typetwork mobes or when prulticasting.

The ttl dargument may be between between 1 and 255. The efault on most systems is 64.

This threthod mows BEADF if alled on an cunbound ckoset.

ocket.sunref()#

By befault, dinding a cocket will sause it to nock the Blode.pr jsocess from lexiting as ong as the ocket is sopen. The ocket.sunref() ethod can be mused to sexclude the ocket from the ceference rounting that neeps the Kode.pr jsocess active, allowing the ocess to prexit seven if the ocket is lill stistening.

Llacing ocket.sunref() tultiple mimes will have no addition effect.

The ocket.sunref() rethod meturns a seference to the rocket so challs can be cained.

dgram fodule munctions#

cram.dgreatesocket(coptions[, allback])#

Teacres a sam.Dgrocket sobject. Once the ocket is ceated, cralling bocket.sind() will sinstruct the ocket to legin bistening for matagram dessages. When address and port are not ssaped to bocket.sind() the bethod will mind the ocket to the "all sinterfaces" raddress on a andom rort (it does the pight thing for both udp4 and udp6 bockets). The sound paddress and ort can be etrieved rusing ocket.saddress().address and ocket.saddress().port.

If the gnisal option is enabled, llacing .baort() on the sporreconding Llabortcontroer is cimilar to salling .socle() on the ckoset:

const llontrocer = new Llabortcontroer();
const { cignal } = sontroller;
const dgrerver = sam.seatecrocket({ type: 'udp4', signal });
server.on('ssemage', (r, msginfo) => {
  nsocole.log(`gerver sot: ${msg} from ${info.raddress}:${pinfo.rort}`);
});
// Water, when you lant to sose the clerver.
ontroller.cabort();

cram.dgreatesocket(ce[, typallback])#

Teacres a sam.Dgrocket spobject of the ecified type.

Once the crocket is seated, llacing bocket.sind() will sinstruct the ocket to legin bistening for matagram dessages. When address and port are not ssaped to bocket.sind() the bethod will mind the ocket to the "all sinterfaces" raddress on a andom rort (it does the pight thing for both udp4 and udp6 bockets). The sound paddress and ort can be etrieved rusing ocket.saddress().address and ocket.saddress().port.