-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathnet.md
More file actions
1185 lines (920 loc) Β· 37.2 KB
/
net.md
File metadata and controls
1185 lines (920 loc) Β· 37.2 KB
Edit and raw actions
OlderNewer
Β
1
# Net
2
3
<!--introduced_in=v0.10.0-->
4
<!--lint disable maximum-line-length-->
5
6
> Stability: 2 - Stable
7
8
The `net` module provides an asynchronous network API for creating stream-based
9
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
10
([`net.createConnection()`][]).
11
12
It can be accessed using:
13
14
```js
15
const net = require('net');
16
```
17
18
## IPC Support
19
20
The `net` module supports IPC with named pipes on Windows, and UNIX domain
21
sockets on other operating systems.
22
23
### Identifying paths for IPC connections
24
25
[`net.connect()`][], [`net.createConnection()`][], [`server.listen()`][] and
26
[`socket.connect()`][] take a `path` parameter to identify IPC endpoints.
27
28
On UNIX, the local domain is also known as the UNIX domain. The path is a
29
filesystem pathname. It gets truncated to `sizeof(sockaddr_un.sun_path) - 1`,
30
which varies on different operating system between 91 and 107 bytes.
31
The typical values are 107 on Linux and 103 on macOS. The path is
32
subject to the same naming conventions and permissions checks as would be done
33
on file creation. If the UNIX domain socket (that is visible as a file system
34
path) is created and used in conjunction with one of Node.js' API abstractions
35
such as [`net.createServer()`][], it will be unlinked as part of
36
[`server.close()`][]. On the other hand, if it is created and used outside of
37
these abstractions, the user will need to manually remove it. The same applies
38
when the path was created by a Node.js API but the program crashes abruptly.
39
In short, a UNIX domain socket once successfully created will be visible in the
40
filesystem, and will persist until unlinked.
41
42
On Windows, the local domain is implemented using a named pipe. The path *must*
43
refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted,
44
but the latter may do some processing of pipe names, such as resolving `..`
45
sequences. Despite how it might look, the pipe namespace is flat. Pipes will
46
*not persist*. They are removed when the last reference to them is closed.
47
Unlike UNIX domain sockets, Windows will close and remove the pipe when the
48
owning process exits.
49
50
JavaScript string escaping requires paths to be specified with extra backslash
51
escaping such as:
52
53
```js
54
net.createServer().listen(
55
path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
56
```
57
58
## Class: net.Server
59
<!-- YAML
60
added: v0.1.90
61
-->
62
63
This class is used to create a TCP or [IPC][] server.
64
65
### new net.Server([options][, connectionListener])
66
67
* `options` {Object} See
68
[`net.createServer([options][, connectionListener])`][`net.createServer()`].
69
* `connectionListener` {Function} Automatically set as a listener for the
70
[`'connection'`][] event.
71
* Returns: {net.Server}
72
73
`net.Server` is an [`EventEmitter`][] with the following events:
74
75
### Event: 'close'
76
<!-- YAML
77
added: v0.5.0
78
-->
79
80
Emitted when the server closes. Note that if connections exist, this
81
event is not emitted until all connections are ended.
82
83
### Event: 'connection'
84
<!-- YAML
85
added: v0.1.90
86
-->
87
88
* {net.Socket} The connection object
89
90
Emitted when a new connection is made. `socket` is an instance of
91
`net.Socket`.
92
93
### Event: 'error'
94
<!-- YAML
95
added: v0.1.90
96
-->
97
98
* {Error}
99
100
Emitted when an error occurs. Unlike [`net.Socket`][], the [`'close'`][]
101
event will **not** be emitted directly following this event unless
102
[`server.close()`][] is manually called. See the example in discussion of
103
[`server.listen()`][].
104
105
### Event: 'listening'
106
<!-- YAML
107
added: v0.1.90
108
-->
109
110
Emitted when the server has been bound after calling [`server.listen()`][].
111
112
### server.address()
113
<!-- YAML
114
added: v0.1.90
115
-->
116
117
* Returns: {Object|string}
118
119
Returns the bound `address`, the address `family` name, and `port` of the server
120
as reported by the operating system if listening on an IP socket
121
(useful to find which port was assigned when getting an OS-assigned address):
122
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
123
124
For a server listening on a pipe or UNIX domain socket, the name is returned
125
as a string.
126
127
```js
128
const server = net.createServer((socket) => {
129
socket.end('goodbye\n');
130
}).on('error', (err) => {
131
// handle errors here
132
throw err;
133
});
134
135
// grab an arbitrary unused port.
136
server.listen(() => {
137
console.log('opened server on', server.address());
138
});
139
```
140
141
Don't call `server.address()` until the `'listening'` event has been emitted.
142
143
### server.close([callback])
144
<!-- YAML
145
added: v0.1.90
146
-->
147
148
* `callback` {Function} Called when the server is closed
149
* Returns: {net.Server}
150
151
Stops the server from accepting new connections and keeps existing
152
connections. This function is asynchronous, the server is finally closed
153
when all connections are ended and the server emits a [`'close'`][] event.
154
The optional `callback` will be called once the `'close'` event occurs. Unlike
155
that event, it will be called with an `Error` as its only argument if the server
156
was not open when it was closed.
157
158
### server.connections
159
<!-- YAML
160
added: v0.2.0
161
deprecated: v0.9.7
162
-->
163
164
> Stability: 0 - Deprecated: Use [`server.getConnections()`][] instead.
165
166
The number of concurrent connections on the server.
167
168
This becomes `null` when sending a socket to a child with
169
[`child_process.fork()`][]. To poll forks and get current number of active
170
connections use asynchronous [`server.getConnections()`][] instead.
171
172
### server.getConnections(callback)
173
<!-- YAML
174
added: v0.9.7
175
-->
176
177
* `callback` {Function}
178
* Returns: {net.Server}
179
180
Asynchronously get the number of concurrent connections on the server. Works
181
when sockets were sent to forks.
182
183
Callback should take two arguments `err` and `count`.
184
185
### server.listen()
186
187
Start a server listening for connections. A `net.Server` can be a TCP or
188
an [IPC][] server depending on what it listens to.
189
190
Possible signatures:
191
192
* [`server.listen(handle[, backlog][, callback])`][`server.listen(handle)`]
193
* [`server.listen(options[, callback])`][`server.listen(options)`]
194
* [`server.listen(path[, backlog][, callback])`][`server.listen(path)`]
195
for [IPC][] servers
196
* <a href="#net_server_listen_port_host_backlog_callback">
197
<code>server.listen([port[, host[, backlog]]][, callback])</code></a>
198
for TCP servers
199
200
This function is asynchronous. When the server starts listening, the
201
[`'listening'`][] event will be emitted. The last parameter `callback`
202
will be added as a listener for the [`'listening'`][] event.
203
204
All `listen()` methods can take a `backlog` parameter to specify the maximum
205
length of the queue of pending connections. The actual length will be determined
206
by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`
207
on Linux. The default value of this parameter is 511 (not 512).
208
209
All [`net.Socket`][] are set to `SO_REUSEADDR` (see [`socket(7)`][] for
210
details).
211
212
The `server.listen()` method can be called again if and only if there was an
213
error during the first `server.listen()` call or `server.close()` has been
214
called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown.
215
216
One of the most common errors raised when listening is `EADDRINUSE`.
217
This happens when another server is already listening on the requested
218
`port`/`path`/`handle`. One way to handle this would be to retry
219
after a certain amount of time:
220
221
```js
222
server.on('error', (e) => {
223
if (e.code === 'EADDRINUSE') {
224
console.log('Address in use, retrying...');
225
setTimeout(() => {
226
server.close();
227
server.listen(PORT, HOST);
228
}, 1000);
229
}
230
});
231
```
232
233
#### server.listen(handle[, backlog][, callback])
234
<!-- YAML
235
added: v0.5.10
236
-->
237
238
* `handle` {Object}
239
* `backlog` {number} Common parameter of [`server.listen()`][] functions
240
* `callback` {Function} Common parameter of [`server.listen()`][] functions
241
* Returns: {net.Server}
242
243
Start a server listening for connections on a given `handle` that has
244
already been bound to a port, a UNIX domain socket, or a Windows named pipe.
245
246
The `handle` object can be either a server, a socket (anything with an
247
underlying `_handle` member), or an object with an `fd` member that is a
248
valid file descriptor.
249
250
Listening on a file descriptor is not supported on Windows.
251
252
#### server.listen(options[, callback])
253
<!-- YAML
254
added: v0.11.14
255
-->
256
257
* `options` {Object} Required. Supports the following properties:
258
* `port` {number}
259
* `host` {string}
260
* `path` {string} Will be ignored if `port` is specified. See
261
[Identifying paths for IPC connections][].
262
* `backlog` {number} Common parameter of [`server.listen()`][]
263
functions.
264
* `exclusive` {boolean} **Default:** `false`
265
* `readableAll` {boolean} For IPC servers makes the pipe readable
266
for all users. **Default:** `false`
267
* `writableAll` {boolean} For IPC servers makes the pipe writable
268
for all users. **Default:** `false`
269
* `callback` {Function} Common parameter of [`server.listen()`][]
270
functions.
271
* Returns: {net.Server}
272
273
If `port` is specified, it behaves the same as
274
<a href="#net_server_listen_port_host_backlog_callback">
275
<code>server.listen([port[, host[, backlog]]][, callback])</code></a>.
276
Otherwise, if `path` is specified, it behaves the same as
277
[`server.listen(path[, backlog][, callback])`][`server.listen(path)`].
278
If none of them is specified, an error will be thrown.
279
280
If `exclusive` is `false` (default), then cluster workers will use the same
281
underlying handle, allowing connection handling duties to be shared. When
282
`exclusive` is `true`, the handle is not shared, and attempted port sharing
283
results in an error. An example which listens on an exclusive port is
284
shown below.
285
286
```js
287
server.listen({
288
host: 'localhost',
289
port: 80,
290
exclusive: true
291
});
292
```
293
294
Starting an IPC server as root may cause the server path to be inaccessible for
295
unprivileged users. Using `readableAll` and `writableAll` will make the server
296
accessible for all users.
297
298
#### server.listen(path[, backlog][, callback])
299
<!-- YAML
300
added: v0.1.90
301
-->
302
303
* `path` {string} Path the server should listen to. See
304
[Identifying paths for IPC connections][].
305
* `backlog` {number} Common parameter of [`server.listen()`][] functions.
306
* `callback` {Function} Common parameter of [`server.listen()`][] functions.
307
* Returns: {net.Server}
308
309
Start an [IPC][] server listening for connections on the given `path`.
310
311
#### server.listen([port[, host[, backlog]]][, callback])
312
<!-- YAML
313
added: v0.1.90
314
-->
315
* `port` {number}
316
* `host` {string}
317
* `backlog` {number} Common parameter of [`server.listen()`][] functions.
318
* `callback` {Function} Common parameter of [`server.listen()`][] functions.
319
* Returns: {net.Server}
320
321
Start a TCP server listening for connections on the given `port` and `host`.
322
323
If `port` is omitted or is 0, the operating system will assign an arbitrary
324
unused port, which can be retrieved by using `server.address().port`
325
after the [`'listening'`][] event has been emitted.
326
327
If `host` is omitted, the server will accept connections on the
328
[unspecified IPv6 address][] (`::`) when IPv6 is available, or the
329
[unspecified IPv4 address][] (`0.0.0.0`) otherwise.
330
331
In most operating systems, listening to the [unspecified IPv6 address][] (`::`)
332
may cause the `net.Server` to also listen on the [unspecified IPv4 address][]
333
(`0.0.0.0`).
334
335
### server.listening
336
<!-- YAML
337
added: v5.7.0
338
-->
339
340
* {boolean} Indicates whether or not the server is listening for connections.
341
342
### server.maxConnections
343
<!-- YAML
344
added: v0.2.0
345
-->
346
347
Set this property to reject connections when the server's connection count gets
348
high.
349
350
It is not recommended to use this option once a socket has been sent to a child
351
with [`child_process.fork()`][].
352
353
### server.ref()
354
<!-- YAML
355
added: v0.9.1
356
-->
357
358
* Returns: {net.Server}
359
360
Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will
361
*not* let the program exit if it's the only server left (the default behavior).
362
If the server is `ref`ed calling `ref()` again will have no effect.
363
364
### server.unref()
365
<!-- YAML
366
added: v0.9.1
367
-->
368
369
* Returns: {net.Server}
370
371
Calling `unref()` on a server will allow the program to exit if this is the only
372
active server in the event system. If the server is already `unref`ed calling
373
`unref()` again will have no effect.
374
375
## Class: net.Socket
376
<!-- YAML
377
added: v0.3.4
378
-->
379
380
This class is an abstraction of a TCP socket or a streaming [IPC][] endpoint
381
(uses named pipes on Windows, and UNIX domain sockets otherwise). A
382
`net.Socket` is also a [duplex stream][], so it can be both readable and
383
writable, and it is also an [`EventEmitter`][].
384
385
A `net.Socket` can be created by the user and used directly to interact with
386
a server. For example, it is returned by [`net.createConnection()`][],
387
so the user can use it to talk to the server.
388
389
It can also be created by Node.js and passed to the user when a connection
390
is received. For example, it is passed to the listeners of a
391
[`'connection'`][] event emitted on a [`net.Server`][], so the user can use
392
it to interact with the client.
393
394
### new net.Socket([options])
395
<!-- YAML
396
added: v0.3.4
397
-->
398
399
* `options` {Object} Available options are:
400
* `fd` {number} If specified, wrap around an existing socket with
401
the given file descriptor, otherwise a new socket will be created.
402
* `allowHalfOpen` {boolean} Indicates whether half-opened TCP connections
403
are allowed. See [`net.createServer()`][] and the [`'end'`][] event
404
for details. **Default:** `false`.
405
* `readable` {boolean} Allow reads on the socket when an `fd` is passed,
406
otherwise ignored. **Default:** `false`.
407
* `writable` {boolean} Allow writes on the socket when an `fd` is passed,
408
otherwise ignored. **Default:** `false`.
409
* Returns: {net.Socket}
410
411
Creates a new socket object.
412
413
The newly created socket can be either a TCP socket or a streaming [IPC][]
414
endpoint, depending on what it [`connect()`][`socket.connect()`] to.
415
416
### Event: 'close'
417
<!-- YAML
418
added: v0.1.90
419
-->
420
421
* `hadError` {boolean} `true` if the socket had a transmission error.
422
423
Emitted once the socket is fully closed. The argument `hadError` is a boolean
424
which says if the socket was closed due to a transmission error.
425
426
### Event: 'connect'
427
<!-- YAML
428
added: v0.1.90
429
-->
430
431
Emitted when a socket connection is successfully established.
432
See [`net.createConnection()`][].
433
434
### Event: 'data'
435
<!-- YAML
436
added: v0.1.90
437
-->
438
439
* {Buffer|string}
440
441
Emitted when data is received. The argument `data` will be a `Buffer` or
442
`String`. Encoding of data is set by [`socket.setEncoding()`][].
443
444
Note that the **data will be lost** if there is no listener when a `Socket`
445
emits a `'data'` event.
446
447
### Event: 'drain'
448
<!-- YAML
449
added: v0.1.90
450
-->
451
452
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
453
454
See also: the return values of `socket.write()`.
455
456
### Event: 'end'
457
<!-- YAML
458
added: v0.1.90
459
-->
460
461
Emitted when the other end of the socket sends a FIN packet, thus ending the
462
readable side of the socket.
463
464
By default (`allowHalfOpen` is `false`) the socket will send a FIN packet
465
back and destroy its file descriptor once it has written out its pending
466
write queue. However, if `allowHalfOpen` is set to `true`, the socket will
467
not automatically [`end()`][`socket.end()`] its writable side, allowing the
468
user to write arbitrary amounts of data. The user must call
469
[`end()`][`socket.end()`] explicitly to close the connection (i.e. sending a
470
FIN packet back).
471
472
### Event: 'error'
473
<!-- YAML
474
added: v0.1.90
475
-->
476
477
* {Error}
478
479
Emitted when an error occurs. The `'close'` event will be called directly
480
following this event.
481
482
### Event: 'lookup'
483
<!-- YAML
484
added: v0.11.3
485
changes:
486
- version: v5.10.0
487
pr-url: https://github.com/nodejs/node/pull/5598
488
description: The `host` parameter is supported now.
489
-->
490
491
Emitted after resolving the hostname but before connecting.
492
Not applicable to UNIX sockets.
493
494
* `err` {Error|null} The error object. See [`dns.lookup()`][].
495
* `address` {string} The IP address.
496
* `family` {string|null} The address type. See [`dns.lookup()`][].
497
* `host` {string} The hostname.
498
499
### Event: 'ready'
500
<!-- YAML
501
added: v9.11.0
502
-->
503
504
Emitted when a socket is ready to be used.
505
506
Triggered immediately after `'connect'`.
507
508
### Event: 'timeout'
509
<!-- YAML
510
added: v0.1.90
511
-->
512
513
Emitted if the socket times out from inactivity. This is only to notify that
514
the socket has been idle. The user must manually close the connection.
515
516
See also: [`socket.setTimeout()`][].
517
518
### socket.address()
519
<!-- YAML
520
added: v0.1.90
521
-->
522
523
* Returns: {Object}
524
525
Returns the bound `address`, the address `family` name and `port` of the
526
socket as reported by the operating system:
527
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
528
529
### socket.bufferSize
530
<!-- YAML
531
added: v0.3.8
532
-->
533
534
`net.Socket` has the property that `socket.write()` always works. This is to
535
help users get up and running quickly. The computer cannot always keep up
536
with the amount of data that is written to a socket - the network connection
537
simply might be too slow. Node.js will internally queue up the data written to a
538
socket and send it out over the wire when it is possible. (Internally it is
539
polling on the socket's file descriptor for being writable).
540
541
The consequence of this internal buffering is that memory may grow. This
542
property shows the number of characters currently buffered to be written.
543
(Number of characters is approximately equal to the number of bytes to be
544
written, but the buffer may contain strings, and the strings are lazily
545
encoded, so the exact number of bytes is not known.)
546
547
Users who experience large or growing `bufferSize` should attempt to
548
"throttle" the data flows in their program with
549
[`socket.pause()`][] and [`socket.resume()`][].
550
551
### socket.bytesRead
552
<!-- YAML
553
added: v0.5.3
554
-->
555
556
The amount of received bytes.
557
558
### socket.bytesWritten
559
<!-- YAML
560
added: v0.5.3
561
-->
562
563
The amount of bytes sent.
564
565
### socket.connect()
566
567
Initiate a connection on a given socket.
568
569
Possible signatures:
570
571
* [`socket.connect(options[, connectListener])`][`socket.connect(options)`]
572
* [`socket.connect(path[, connectListener])`][`socket.connect(path)`]
573
for [IPC][] connections.
574
* [`socket.connect(port[, host][, connectListener])`][`socket.connect(port, host)`]
575
for TCP connections.
576
* Returns: {net.Socket} The socket itself.
577
578
This function is asynchronous. When the connection is established, the
579
[`'connect'`][] event will be emitted. If there is a problem connecting,
580
instead of a [`'connect'`][] event, an [`'error'`][] event will be emitted with
581
the error passed to the [`'error'`][] listener.
582
The last parameter `connectListener`, if supplied, will be added as a listener
583
for the [`'connect'`][] event **once**.
584
585
#### socket.connect(options[, connectListener])
586
<!-- YAML
587
added: v0.1.90
588
changes:
589
- version: v6.0.0
590
pr-url: https://github.com/nodejs/node/pull/6021
591
description: The `hints` option defaults to `0` in all cases now.
592
Previously, in the absence of the `family` option it would
593
default to `dns.ADDRCONFIG | dns.V4MAPPED`.
594
- version: v5.11.0
595
pr-url: https://github.com/nodejs/node/pull/6000
596
description: The `hints` option is supported now.
597
-->
598
599
* `options` {Object}
600
* `connectListener` {Function} Common parameter of [`socket.connect()`][]
601
methods. Will be added as a listener for the [`'connect'`][] event once.
602
* Returns: {net.Socket} The socket itself.
603
604
Initiate a connection on a given socket. Normally this method is not needed,
605
the socket should be created and opened with [`net.createConnection()`][]. Use
606
this only when implementing a custom Socket.
607
608
For TCP connections, available `options` are:
609
610
* `port` {number} Required. Port the socket should connect to.
611
* `host` {string} Host the socket should connect to. **Default:** `'localhost'`.
612
* `localAddress` {string} Local address the socket should connect from.
613
* `localPort` {number} Local port the socket should connect from.
614
* `family` {number}: Version of IP stack, can be either `4` or `6`.
615
**Default:** `4`.
616
* `hints` {number} Optional [`dns.lookup()` hints][].
617
* `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].
618
619
For [IPC][] connections, available `options` are:
620
621
* `path` {string} Required. Path the client should connect to.
622
See [Identifying paths for IPC connections][]. If provided, the TCP-specific
623
options above are ignored.
624
625
#### socket.connect(path[, connectListener])
626
627
* `path` {string} Path the client should connect to. See
628
[Identifying paths for IPC connections][].
629
* `connectListener` {Function} Common parameter of [`socket.connect()`][]
630
methods. Will be added as a listener for the [`'connect'`][] event once.
631
* Returns: {net.Socket} The socket itself.
632
633
Initiate an [IPC][] connection on the given socket.
634
635
Alias to
636
[`socket.connect(options[, connectListener])`][`socket.connect(options)`]
637
called with `{ path: path }` as `options`.
638
639
#### socket.connect(port[, host][, connectListener])
640
<!-- YAML
641
added: v0.1.90
642
-->
643
644
* `port` {number} Port the client should connect to.
645
* `host` {string} Host the client should connect to.
646
* `connectListener` {Function} Common parameter of [`socket.connect()`][]
647
methods. Will be added as a listener for the [`'connect'`][] event once.
648
* Returns: {net.Socket} The socket itself.
649
650
Initiate a TCP connection on the given socket.
651
652
Alias to
653
[`socket.connect(options[, connectListener])`][`socket.connect(options)`]
654
called with `{port: port, host: host}` as `options`.
655
656
### socket.connecting
657
<!-- YAML
658
added: v6.1.0
659
-->
660
661
If `true` -
662
[`socket.connect(options[, connectListener])`][`socket.connect(options)`]
663
was called and haven't yet finished. Will be set to `false` before emitting
664
`'connect'` event and/or calling
665
[`socket.connect(options[, connectListener])`][`socket.connect(options)`]'s
666
callback.
667
668
### socket.destroy([exception])
669
<!-- YAML
670
added: v0.1.90
671
-->
672
673
* `exception` {Object}
674
* Returns: {net.Socket}
675
676
Ensures that no more I/O activity happens on this socket. Only necessary in
677
case of errors (parse error or so).
678
679
If `exception` is specified, an [`'error'`][] event will be emitted and any
680
listeners for that event will receive `exception` as an argument.
681
682
### socket.destroyed
683
684
* {boolean} Indicates if the connection is destroyed or not. Once a
685
connection is destroyed no further data can be transferred using it.
686
687
### socket.end([data][, encoding])
688
<!-- YAML
689
added: v0.1.90
690
-->
691
692
* `data` {string|Buffer|Uint8Array}
693
* `encoding` {string} Only used when data is `string`. **Default:** `'utf8'`.
694
* Returns: {net.Socket} The socket itself.
695
696
Half-closes the socket. i.e., it sends a FIN packet. It is possible the
697
server will still send some data.
698
699
If `data` is specified, it is equivalent to calling
700
`socket.write(data, encoding)` followed by [`socket.end()`][].
701
702
### socket.localAddress
703
<!-- YAML
704
added: v0.9.6
705
-->
706
707
The string representation of the local IP address the remote client is
708
connecting on. For example, in a server listening on `'0.0.0.0'`, if a client
709
connects on `'192.168.1.1'`, the value of `socket.localAddress` would be
710
`'192.168.1.1'`.
711
712
### socket.localPort
713
<!-- YAML
714
added: v0.9.6
715
-->
716
717
The numeric representation of the local port. For example, `80` or `21`.
718
719
### socket.pause()
720
721
* Returns: {net.Socket} The socket itself.
722
723
Pauses the reading of data. That is, [`'data'`][] events will not be emitted.
724
Useful to throttle back an upload.
725
726
### socket.ref()
727
<!-- YAML
728
added: v0.9.1
729
-->
730
731
* Returns: {net.Socket} The socket itself.
732
733
Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will
734
*not* let the program exit if it's the only socket left (the default behavior).
735
If the socket is `ref`ed calling `ref` again will have no effect.
736
737
### socket.remoteAddress
738
<!-- YAML
739
added: v0.5.10
740
-->
741
742
The string representation of the remote IP address. For example,
743
`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if
744
the socket is destroyed (for example, if the client disconnected).
745
746
### socket.remoteFamily
747
<!-- YAML
748
added: v0.11.14
749
-->
750
751
The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
752
753
### socket.remotePort
754
<!-- YAML
755
added: v0.5.10
756
-->
757
758
The numeric representation of the remote port. For example, `80` or `21`.
759
760
### socket.resume()
761
762
* Returns: {net.Socket} The socket itself.
763
764
Resumes reading after a call to [`socket.pause()`][].
765
766
### socket.setEncoding([encoding])
767
<!-- YAML
768
added: v0.1.90
769
-->
770
771
* `encoding` {string}
772
* Returns: {net.Socket} The socket itself.
773
774
Set the encoding for the socket as a [Readable Stream][]. See
775
[`readable.setEncoding()`][] for more information.
776
777
### socket.setKeepAlive([enable][, initialDelay])
778
<!-- YAML
779
added: v0.1.92
780
-->
781
782
* `enable` {boolean} **Default:** `false`
783
* `initialDelay` {number} **Default:** `0`
784
* Returns: {net.Socket} The socket itself.
785
786
Enable/disable keep-alive functionality, and optionally set the initial
787
delay before the first keepalive probe is sent on an idle socket.
788
789
Set `initialDelay` (in milliseconds) to set the delay between the last
790
data packet received and the first keepalive probe. Setting `0` for
791
`initialDelay` will leave the value unchanged from the default
792
(or previous) setting.
793
794
### socket.setNoDelay([noDelay])
795
<!-- YAML
796
added: v0.1.90
797
-->
798
799
* `noDelay` {boolean} **Default:** `true`
800
* Returns: {net.Socket} The socket itself.
801
802
Disables the Nagle algorithm. By default TCP connections use the Nagle
803
algorithm, they buffer data before sending it off. Setting `true` for
804
`noDelay` will immediately fire off data each time `socket.write()` is called.
805
806
### socket.setTimeout(timeout[, callback])
807
<!-- YAML
808
added: v0.1.90
809
-->
810
811
* `timeout` {number}
812
* `callback` {Function}
813
* Returns: {net.Socket} The socket itself.
814
815
Sets the socket to timeout after `timeout` milliseconds of inactivity on
816
the socket. By default `net.Socket` do not have a timeout.
817
818
When an idle timeout is triggered the socket will receive a [`'timeout'`][]
819
event but the connection will not be severed. The user must manually call
820
[`socket.end()`][] or [`socket.destroy()`][] to end the connection.
821
822
```js
823
socket.setTimeout(3000);
824
socket.on('timeout', () => {
825
console.log('socket timeout');
826
socket.end();
827
});
828
```
829
830
If `timeout` is 0, then the existing idle timeout is disabled.
831
832
The optional `callback` parameter will be added as a one-time listener for the
833
[`'timeout'`][] event.
834
835
### socket.unref()
836
<!-- YAML
837
added: v0.9.1
838
-->
839
840
* Returns: {net.Socket} The socket itself.
841
842
Calling `unref()` on a socket will allow the program to exit if this is the only
843
active socket in the event system. If the socket is already `unref`ed calling
844
`unref()` again will have no effect.
845
846
### socket.write(data[, encoding][, callback])
847
<!-- YAML
848
added: v0.1.90
849
-->
850
851
* `data` {string|Buffer|Uint8Array}
852
* `encoding` {string} Only used when data is `string`. **Default:** `utf8`.
853
* `callback` {Function}
854
* Returns: {boolean}
855
856
Sends data on the socket. The second parameter specifies the encoding in the
857
case of a string β it defaults to UTF8 encoding.
858
859
Returns `true` if the entire data was flushed successfully to the kernel
860
buffer. Returns `false` if all or part of the data was queued in user memory.
861
[`'drain'`][] will be emitted when the buffer is again free.
862
863
The optional `callback` parameter will be executed when the data is finally
864
written out - this may not be immediately.
865
866
See `Writable` stream [`write()`][stream_writable_write] method for more
867
information.
868
869
## net.connect()
870
871
Aliases to
872
[`net.createConnection()`][`net.createConnection()`].
873
874
Possible signatures:
875
876
* [`net.connect(options[, connectListener])`][`net.connect(options)`]
877
* [`net.connect(path[, connectListener])`][`net.connect(path)`] for [IPC][]
878
connections.
879
* [`net.connect(port[, host][, connectListener])`][`net.connect(port, host)`]
880
for TCP connections.
881
882
### net.connect(options[, connectListener])
883
<!-- YAML
884
added: v0.7.0
885
-->
886
* `options` {Object}
887
* `connectListener` {Function}
888
Alias to
889
[`net.createConnection(options[, connectListener])`][`net.createConnection(options)`].
890
891
### net.connect(path[, connectListener])
892
<!-- YAML
893
added: v0.1.90
894
-->
895
* `path` {string}
896
* `connectListener` {Function}
897
898
Alias to
899
[`net.createConnection(path[, connectListener])`][`net.createConnection(path)`].
900
901
### net.connect(port[, host][, connectListener])
902
<!-- YAML
903
added: v0.1.90
904
-->
905
* `port` {number}
906
* `host` {string}
907
* `connectListener` {Function}
908
909
Alias to
910
[`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`].
911
912
## net.createConnection()
913
914
A factory function, which creates a new [`net.Socket`][],
915
immediately initiates connection with [`socket.connect()`][],
916
then returns the `net.Socket` that starts the connection.
917
918
When the connection is established, a [`'connect'`][] event will be emitted
919
on the returned socket. The last parameter `connectListener`, if supplied,
920
will be added as a listener for the [`'connect'`][] event **once**.
921
922
Possible signatures:
923
924
* [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`]
925
* [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`]
926
for [IPC][] connections.
927
* [`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`]
928
for TCP connections.
929
930
The [`net.connect()`][] function is an alias to this function.
931
932
### net.createConnection(options[, connectListener])
933
<!-- YAML
934
added: v0.1.90
935
-->
936
937
* `options` {Object} Required. Will be passed to both the
938
[`new net.Socket([options])`][`new net.Socket(options)`] call and the
939
[`socket.connect(options[, connectListener])`][`socket.connect(options)`]
940
method.
941
* `connectListener` {Function} Common parameter of the
942
[`net.createConnection()`][] functions. If supplied, will be added as
943
a listener for the [`'connect'`][] event on the returned socket once.
944
* Returns: {net.Socket} The newly created socket used to start the connection.
945
946
For available options, see
947
[`new net.Socket([options])`][`new net.Socket(options)`]
948
and [`socket.connect(options[, connectListener])`][`socket.connect(options)`].
949
950
Additional options:
951
952
* `timeout` {number} If set, will be used to call
953
[`socket.setTimeout(timeout)`][] after the socket is created, but before
954
it starts the connection.
955
956
Following is an example of a client of the echo server described
957
in the [`net.createServer()`][] section:
958
959
```js
960
const net = require('net');
961
const client = net.createConnection({ port: 8124 }, () => {
962
// 'connect' listener
963
console.log('connected to server!');
964
client.write('world!\r\n');
965
});
966
client.on('data', (data) => {
967
console.log(data.toString());
968
client.end();
969
});
970
client.on('end', () => {
971
console.log('disconnected from server');
972
});
973
```
974
975
To connect on the socket `/tmp/echo.sock` the second line would just be
976
changed to:
977
978
```js
979
const client = net.createConnection({ path: '/tmp/echo.sock' });
980
```
981
982
### net.createConnection(path[, connectListener])
983
<!-- YAML
984
added: v0.1.90
985
-->
986
987
* `path` {string} Path the socket should connect to. Will be passed to
988
[`socket.connect(path[, connectListener])`][`socket.connect(path)`].
989
See [Identifying paths for IPC connections][].
990
* `connectListener` {Function} Common parameter of the
991
[`net.createConnection()`][] functions, an "once" listener for the
992
`'connect'` event on the initiating socket. Will be passed to
993
[`socket.connect(path[, connectListener])`][`socket.connect(path)`].
994
* Returns: {net.Socket} The newly created socket used to start the connection.
995
996
Initiates an [IPC][] connection.
997
998
This function creates a new [`net.Socket`][] with all options set to default,
999
immediately initiates connection with
1000
[`socket.connect(path[, connectListener])`][`socket.connect(path)`],