Browse Source

doc: sort net alphabetically

Reorders, with minimal contextual duplication, the net documentation
alphabetically.

PR-URL: https://github.com/nodejs/node/pull/3662
Reviewed-By: Evan Lucas <evanlucas@me.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Jeremiah Senkpiel <fishrock123@rocketmail.com>
process-exit-stdio-flushing
Tristian Flanagan 9 years ago
committed by James M Snell
parent
commit
403d2bffa6
  1. 713
      doc/api/net.markdown

713
doc/api/net.markdown

@ -6,176 +6,82 @@ The `net` module provides you with an asynchronous network wrapper. It contains
functions for creating both servers and clients (called streams). You can include functions for creating both servers and clients (called streams). You can include
this module with `require('net');`. this module with `require('net');`.
## net.createServer([options][, connectionListener]) ## Class: net.Server
Creates a new server. The `connectionListener` argument is
automatically set as a listener for the ['connection'][] event.
`options` is an object with the following defaults:
{
allowHalfOpen: false,
pauseOnConnect: false
}
If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN This class is used to create a TCP or local server.
packet when the other end of the socket sends a FIN packet. The socket becomes
non-readable, but still writable. You should call the `end()` method explicitly.
See ['end'][] event for more information.
If `pauseOnConnect` is `true`, then the socket associated with each incoming `net.Server` is an [EventEmitter][] with the following events:
connection will be paused, and no data will be read from its handle. This allows
connections to be passed between processes without any data being read by the
original process. To begin reading data from a paused socket, call `resume()`.
Here is an example of an echo server which listens for connections ### Event: 'close'
on port 8124:
var net = require('net'); Emitted when the server closes. Note that if connections exist, this
var server = net.createServer(function(c) { //'connection' listener event is not emitted until all connections are ended.
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});
Test this by using `telnet`: ### Event: 'connection'
telnet localhost 8124 * {Socket object} The connection object
To listen on the socket `/tmp/echo.sock` the third line from the last would Emitted when a new connection is made. `socket` is an instance of
just be changed to `net.Socket`.
server.listen('/tmp/echo.sock', function() { //'listening' listener ### Event: 'error'
Use `nc` to connect to a UNIX domain socket server: * {Error Object}
nc -U /tmp/echo.sock Emitted when an error occurs. The ['close'][] event will be called directly
following this event. See example in discussion of `server.listen`.
## net.connect(options[, connectListener]) ### Event: 'listening'
## net.createConnection(options[, connectListener])
A factory function, which returns a new ['net.Socket'](#net_class_net_socket) Emitted when the server has been bound after calling `server.listen`.
and automatically connects with the supplied `options`.
The options are passed to both the ['net.Socket'](#net_class_net_socket) ### server.address()
constructor and the ['socket.connect'](#net_socket_connect_options_connectlistener)
method.
The `connectListener` parameter will be added as a listener for the Returns the bound address, the address family name and port of the server
['connect'][] event once. as reported by the operating system.
Useful to find which port was assigned when giving getting an OS-assigned address.
Returns an object with three properties, e.g.
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
Here is an example of a client of the previously described echo server: Example:
var net = require('net'); var server = net.createServer(function (socket) {
var client = net.connect({port: 8124}, socket.end("goodbye\n");
function() { //'connect' listener
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('disconnected from server');
}); });
To connect on the socket `/tmp/echo.sock` the second line would just be // grab a random port.
changed to server.listen(function() {
address = server.address();
var client = net.connect({path: '/tmp/echo.sock'}); console.log("opened server on %j", address);
## net.connect(port[, host][, connectListener])
## net.createConnection(port[, host][, connectListener])
A factory function, which returns a new
['net.Socket'](#net_class_net_socket) and automatically connects to the
supplied `port` and `host`.
If `host` is omitted, `'localhost'` will be assumed.
The `connectListener` parameter will be added as a listener for the
['connect'][] event once.
## net.connect(path[, connectListener])
## net.createConnection(path[, connectListener])
A factory function, which returns a new unix
['net.Socket'](#net_class_net_socket) and automatically connects to the
supplied `path`.
The `connectListener` parameter will be added as a listener for the
['connect'][] event once.
## Class: net.Server
This class is used to create a TCP or local server.
### server.listen(port[, hostname][, backlog][, callback])
Begin accepting connections on the specified `port` and `hostname`. If the
`hostname` is omitted, the server will accept connections on any IPv6 address
(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
port value of zero will assign a random port.
Backlog is the maximum length of the queue of pending connections.
The actual length will be determined by your OS through sysctl settings such as
`tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
parameter is 511 (not 512).
This function is asynchronous. When the server has been bound,
['listening'][] event will be emitted. The last parameter `callback`
will be added as a listener for the ['listening'][] event.
One issue some users run into is getting `EADDRINUSE` errors. This means that
another server is already running on the requested port. One way of handling this
would be to wait a second and then try again. This can be done with
server.on('error', function (e) {
if (e.code == 'EADDRINUSE') {
console.log('Address in use, retrying...');
setTimeout(function () {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
}); });
(Note: All sockets in Node.js set `SO_REUSEADDR` already) Don't call `server.address()` until the `'listening'` event has been emitted.
### server.close([callback])
### server.listen(path[, callback]) Stops the server from accepting new connections and keeps existing
connections. This function is asynchronous, the server is finally
closed when all connections are ended and the server emits a ['close'][] event.
The optional `callback` will be called once the `'close'` event occurs. Unlike
that event, it will be called with an Error as its only argument if the server
was not open when it was closed.
* `path` {String} ### server.connections
* `callback` {Function}
Start a local socket server listening for connections on the given `path`. Stability: 0 - Deprecated: Use [server.getConnections][] instead.
This function is asynchronous. When the server has been bound, The number of concurrent connections on the server.
['listening'][] event will be emitted. The last parameter `callback`
will be added as a listener for the ['listening'][] event.
On UNIX, the local domain is usually known as the UNIX domain. The path is a This becomes `null` when sending a socket to a child with
filesystem path name. It is subject to the same naming conventions and `child_process.fork()`. To poll forks and get current number of active
permissions checks as would be done on file creation, will be visible in the connections use asynchronous `server.getConnections` instead.
filesystem, and will *persist until unlinked*.
On Windows, the local domain is implemented using a named pipe. The path *must* ### server.getConnections(callback)
refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted,
but the latter may do some processing of pipe names, such as resolving `..`
sequences. Despite appearances, the pipe name space is flat. Pipes will *not
persist*, they are removed when the last reference to them is closed. Do not
forget JavaScript string escaping requires paths to be specified with
double-backslashes, such as:
net.createServer().listen( Asynchronously get the number of concurrent connections on the server. Works
path.join('\\\\?\\pipe', process.cwd(), 'myctl')) when sockets were sent to forks.
Callback should take two arguments `err` and `count`.
### server.listen(handle[, callback]) ### server.listen(handle[, callback])
@ -224,52 +130,64 @@ shown below.
exclusive: true exclusive: true
}); });
### server.close([callback]) ### server.listen(path[, callback])
Stops the server from accepting new connections and keeps existing * `path` {String}
connections. This function is asynchronous, the server is finally * `callback` {Function}
closed when all connections are ended and the server emits a ['close'][] event.
The optional `callback` will be called once the `'close'` event occurs. Unlike
that event, it will be called with an Error as its only argument if the server
was not open when it was closed.
### server.address() Start a local socket server listening for connections on the given `path`.
Returns the bound address, the address family name and port of the server This function is asynchronous. When the server has been bound,
as reported by the operating system. ['listening'][] event will be emitted. The last parameter `callback`
Useful to find which port was assigned when giving getting an OS-assigned address. will be added as a listener for the ['listening'][] event.
Returns an object with three properties, e.g.
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
Example: On UNIX, the local domain is usually known as the UNIX domain. The path is a
filesystem path name. It is subject to the same naming conventions and
permissions checks as would be done on file creation, will be visible in the
filesystem, and will *persist until unlinked*.
var server = net.createServer(function (socket) { On Windows, the local domain is implemented using a named pipe. The path *must*
socket.end("goodbye\n"); refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted,
}); but the latter may do some processing of pipe names, such as resolving `..`
sequences. Despite appearances, the pipe name space is flat. Pipes will *not
persist*, they are removed when the last reference to them is closed. Do not
forget JavaScript string escaping requires paths to be specified with
double-backslashes, such as:
// grab a random port. net.createServer().listen(
server.listen(function() { path.join('\\\\?\\pipe', process.cwd(), 'myctl'))
address = server.address();
console.log("opened server on %j", address);
});
Don't call `server.address()` until the `'listening'` event has been emitted. ### server.listen(port[, hostname][, backlog][, callback])
### server.unref() Begin accepting connections on the specified `port` and `hostname`. If the
`hostname` is omitted, the server will accept connections on any IPv6 address
(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
port value of zero will assign a random port.
Calling `unref` on a server will allow the program to exit if this is the only Backlog is the maximum length of the queue of pending connections.
active server in the event system. If the server is already `unref`d calling The actual length will be determined by your OS through sysctl settings such as
`unref` again will have no effect. `tcp_max_syn_backlog` and `somaxconn` on linux. The default value of this
parameter is 511 (not 512).
Returns `server`. This function is asynchronous. When the server has been bound,
['listening'][] event will be emitted. The last parameter `callback`
will be added as a listener for the ['listening'][] event.
### server.ref() One issue some users run into is getting `EADDRINUSE` errors. This means that
another server is already running on the requested port. One way of handling this
would be to wait a second and then try again. This can be done with
Opposite of `unref`, calling `ref` on a previously `unref`d server will *not* server.on('error', function (e) {
let the program exit if it's the only server left (the default behavior). If if (e.code == 'EADDRINUSE') {
the server is `ref`d calling `ref` again will have no effect. console.log('Address in use, retrying...');
setTimeout(function () {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});
Returns `server`. (Note: All sockets in Node.js set `SO_REUSEADDR` already)
### server.maxConnections ### server.maxConnections
@ -279,47 +197,21 @@ high.
It is not recommended to use this option once a socket has been sent to a child It is not recommended to use this option once a socket has been sent to a child
with `child_process.fork()`. with `child_process.fork()`.
### server.connections ### server.ref()
Stability: 0 - Deprecated: Use [server.getConnections][] instead.
The number of concurrent connections on the server.
This becomes `null` when sending a socket to a child with
`child_process.fork()`. To poll forks and get current number of active
connections use asynchronous `server.getConnections` instead.
### server.getConnections(callback)
Asynchronously get the number of concurrent connections on the server. Works
when sockets were sent to forks.
Callback should take two arguments `err` and `count`.
`net.Server` is an [EventEmitter][] with the following events:
### Event: 'listening'
Emitted when the server has been bound after calling `server.listen`.
### Event: 'connection'
* {Socket object} The connection object
Emitted when a new connection is made. `socket` is an instance of
`net.Socket`.
### Event: 'close' Opposite of `unref`, calling `ref` on a previously `unref`d server will *not*
let the program exit if it's the only server left (the default behavior). If
the server is `ref`d calling `ref` again will have no effect.
Emitted when the server closes. Note that if connections exist, this Returns `server`.
event is not emitted until all connections are ended.
### Event: 'error' ### server.unref()
* {Error Object} Calling `unref` on a server will allow the program to exit if this is the only
active server in the event system. If the server is already `unref`d calling
`unref` again will have no effect.
Emitted when an error occurs. The ['close'][] event will be called directly Returns `server`.
following this event. See example in discussion of `server.listen`.
## Class: net.Socket ## Class: net.Socket
@ -345,44 +237,76 @@ Set `readable` and/or `writable` to `true` to allow reads and/or writes on this
socket (NOTE: Works only when `fd` is passed). socket (NOTE: Works only when `fd` is passed).
About `allowHalfOpen`, refer to `createServer()` and `'end'` event. About `allowHalfOpen`, refer to `createServer()` and `'end'` event.
### socket.connect(options[, connectListener]) `net.Socket` instances are [EventEmitter][] with the following events:
Opens the connection for a given socket. ### Event: 'close'
For TCP sockets, `options` argument should be an object which specifies: * `had_error` {Boolean} `true` if the socket had a transmission error.
- `port`: Port the client should connect to (Required). Emitted once the socket is fully closed. The argument `had_error` is a boolean
which says if the socket was closed due to a transmission error.
- `host`: Host the client should connect to. Defaults to `'localhost'`. ### Event: 'connect'
- `localAddress`: Local interface to bind to for network connections. Emitted when a socket connection is successfully established.
See `connect()`.
- `localPort`: Local port to bind to for network connections. ### Event: 'data'
- `family` : Version of IP stack. Defaults to `4`. * {Buffer object}
- `lookup` : Custom lookup function. Defaults to `dns.lookup`. Emitted when data is received. The argument `data` will be a `Buffer` or
`String`. Encoding of data is set by `socket.setEncoding()`.
(See the [Readable Stream][] section for more information.)
For local domain sockets, `options` argument should be an object which Note that the __data will be lost__ if there is no listener when a `Socket`
specifies: emits a `'data'` event.
- `path`: Path the client should connect to (Required). ### Event: 'drain'
Normally this method is not needed, as `net.createConnection` opens the Emitted when the write buffer becomes empty. Can be used to throttle uploads.
socket. Use this only if you are implementing a custom Socket.
This function is asynchronous. When the ['connect'][] event is emitted the See also: the return values of `socket.write()`
socket is established. If there is a problem connecting, the `'connect'` event
will not be emitted, the `'error'` event will be emitted with the exception.
The `connectListener` parameter will be added as a listener for the ### Event: 'end'
['connect'][] event.
### socket.connect(port[, host][, connectListener]) Emitted when the other end of the socket sends a FIN packet.
### socket.connect(path[, connectListener])
As [socket.connect(options[, connectListener])](#net_socket_connect_options_connectlistener), By default (`allowHalfOpen == false`) the socket will destroy its file
with options either as either `{port: port, host: host}` or `{path: path}`. descriptor once it has written out its pending write queue. However, by
setting `allowHalfOpen == true` the socket will not automatically `end()`
its side allowing the user to write arbitrary amounts of data, with the
caveat that the user is required to `end()` their side now.
### Event: 'error'
* {Error object}
Emitted when an error occurs. The `'close'` event will be called directly
following this event.
### Event: 'lookup'
Emitted after resolving the hostname but before connecting.
Not applicable to UNIX sockets.
* `err` {Error | Null} The error object. See [dns.lookup()][].
* `address` {String} The IP address.
* `family` {String | Null} The address type. See [dns.lookup()][].
### Event: 'timeout'
Emitted if the socket times out from inactivity. This is only to notify that
the socket has been idle. The user must manually close the connection.
See also: `socket.setTimeout()`
### socket.address()
Returns the bound address, the address family name and port of the
socket as reported by the operating system. Returns an object with
three properties, e.g.
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
### socket.bufferSize ### socket.bufferSize
@ -402,23 +326,57 @@ encoded, so the exact number of bytes is not known.)
Users who experience large or growing `bufferSize` should attempt to Users who experience large or growing `bufferSize` should attempt to
"throttle" the data flows in their program with `pause()` and `resume()`. "throttle" the data flows in their program with `pause()` and `resume()`.
### socket.bytesRead
### socket.setEncoding([encoding]) The amount of received bytes.
Set the encoding for the socket as a Readable Stream. See ### socket.bytesWritten
[stream.setEncoding()][] for more information.
### socket.write(data[, encoding][, callback]) The amount of bytes sent.
Sends data on the socket. The second parameter specifies the encoding in the ### socket.connect(options[, connectListener])
case of a string--it defaults to UTF8 encoding.
Returns `true` if the entire data was flushed successfully to the kernel Opens the connection for a given socket.
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is again free.
The optional `callback` parameter will be executed when the data is finally For TCP sockets, `options` argument should be an object which specifies:
written out - this may not be immediately.
- `port`: Port the client should connect to (Required).
- `host`: Host the client should connect to. Defaults to `'localhost'`.
- `localAddress`: Local interface to bind to for network connections.
- `localPort`: Local port to bind to for network connections.
- `family` : Version of IP stack. Defaults to `4`.
- `lookup` : Custom lookup function. Defaults to `dns.lookup`.
For local domain sockets, `options` argument should be an object which
specifies:
- `path`: Path the client should connect to (Required).
Normally this method is not needed, as `net.createConnection` opens the
socket. Use this only if you are implementing a custom Socket.
This function is asynchronous. When the ['connect'][] event is emitted the
socket is established. If there is a problem connecting, the `'connect'` event
will not be emitted, the `'error'` event will be emitted with the exception.
The `connectListener` parameter will be added as a listener for the
['connect'][] event.
### socket.connect(path[, connectListener])
### socket.connect(port[, host][, connectListener])
As [socket.connect(options[, connectListener])](#net_socket_connect_options_connectlistener),
with options either as either `{port: port, host: host}` or `{path: path}`.
### socket.destroy()
Ensures that no more I/O activity happens on this socket. Only necessary in
case of errors (parse error or so).
### socket.end([data][, encoding]) ### socket.end([data][, encoding])
@ -428,44 +386,52 @@ server will still send some data.
If `data` is specified, it is equivalent to calling If `data` is specified, it is equivalent to calling
`socket.write(data, encoding)` followed by `socket.end()`. `socket.write(data, encoding)` followed by `socket.end()`.
### socket.destroy() ### socket.localAddress
Ensures that no more I/O activity happens on this socket. Only necessary in The string representation of the local IP address the remote client is
case of errors (parse error or so). connecting on. For example, if you are listening on `'0.0.0.0'` and the
client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`.
### socket.localPort
The numeric representation of the local port. For example,
`80` or `21`.
### socket.pause() ### socket.pause()
Pauses the reading of data. That is, `'data'` events will not be emitted. Pauses the reading of data. That is, `'data'` events will not be emitted.
Useful to throttle back an upload. Useful to throttle back an upload.
### socket.resume() ### socket.ref()
Resumes reading after a call to `pause()`. Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not*
let the program exit if it's the only socket left (the default behavior). If
the socket is `ref`d calling `ref` again will have no effect.
### socket.setTimeout(timeout[, callback]) Returns `socket`.
Sets the socket to timeout after `timeout` milliseconds of inactivity on ### socket.remoteAddress
the socket. By default `net.Socket` do not have a timeout.
When an idle timeout is triggered the socket will receive a `'timeout'` The string representation of the remote IP address. For example,
event but the connection will not be severed. The user must manually `end()` `'74.125.127.100'` or `'2001:4860:a005::68'`.
or `destroy()` the socket.
If `timeout` is 0, then the existing idle timeout is disabled. ### socket.remoteFamily
The optional `callback` parameter will be added as a one time listener for the The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
`'timeout'` event.
Returns `socket`. ### socket.remotePort
### socket.setNoDelay([noDelay]) The numeric representation of the remote port. For example,
`80` or `21`.
Disables the Nagle algorithm. By default TCP connections use the Nagle ### socket.resume()
algorithm, they buffer data before sending it off. Setting `true` for
`noDelay` will immediately fire off data each time `socket.write()` is called.
`noDelay` defaults to `true`.
Returns `socket`. Resumes reading after a call to `pause()`.
### socket.setEncoding([encoding])
Set the encoding for the socket as a Readable Stream. See
[stream.setEncoding()][] for more information.
### socket.setKeepAlive([enable][, initialDelay]) ### socket.setKeepAlive([enable][, initialDelay])
@ -480,12 +446,30 @@ initialDelay will leave the value unchanged from the default
Returns `socket`. Returns `socket`.
### socket.address() ### socket.setNoDelay([noDelay])
Returns the bound address, the address family name and port of the Disables the Nagle algorithm. By default TCP connections use the Nagle
socket as reported by the operating system. Returns an object with algorithm, they buffer data before sending it off. Setting `true` for
three properties, e.g. `noDelay` will immediately fire off data each time `socket.write()` is called.
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` `noDelay` defaults to `true`.
Returns `socket`.
### socket.setTimeout(timeout[, callback])
Sets the socket to timeout after `timeout` milliseconds of inactivity on
the socket. By default `net.Socket` do not have a timeout.
When an idle timeout is triggered the socket will receive a `'timeout'`
event but the connection will not be severed. The user must manually `end()`
or `destroy()` the socket.
If `timeout` is 0, then the existing idle timeout is disabled.
The optional `callback` parameter will be added as a one time listener for the
`'timeout'` event.
Returns `socket`.
### socket.unref() ### socket.unref()
@ -495,113 +479,174 @@ active socket in the event system. If the socket is already `unref`d calling
Returns `socket`. Returns `socket`.
### socket.ref() ### socket.write(data[, encoding][, callback])
Opposite of `unref`, calling `ref` on a previously `unref`d socket will *not* Sends data on the socket. The second parameter specifies the encoding in the
let the program exit if it's the only socket left (the default behavior). If case of a string--it defaults to UTF8 encoding.
the socket is `ref`d calling `ref` again will have no effect.
Returns `socket`. Returns `true` if the entire data was flushed successfully to the kernel
buffer. Returns `false` if all or part of the data was queued in user memory.
`'drain'` will be emitted when the buffer is again free.
### socket.remoteAddress The optional `callback` parameter will be executed when the data is finally
written out - this may not be immediately.
The string representation of the remote IP address. For example, ## net.connect(options[, connectListener])
`'74.125.127.100'` or `'2001:4860:a005::68'`.
### socket.remoteFamily A factory function, which returns a new ['net.Socket'](#net_class_net_socket)
and automatically connects with the supplied `options`.
The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. The options are passed to both the ['net.Socket'](#net_class_net_socket)
constructor and the ['socket.connect'](#net_socket_connect_options_connectlistener)
method.
### socket.remotePort The `connectListener` parameter will be added as a listener for the
['connect'][] event once.
The numeric representation of the remote port. For example, Here is an example of a client of the previously described echo server:
`80` or `21`.
### socket.localAddress var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('disconnected from server');
});
The string representation of the local IP address the remote client is To connect on the socket `/tmp/echo.sock` the second line would just be
connecting on. For example, if you are listening on `'0.0.0.0'` and the changed to
client connects on `'192.168.1.1'`, the value would be `'192.168.1.1'`.
### socket.localPort var client = net.connect({path: '/tmp/echo.sock'});
The numeric representation of the local port. For example, ## net.connect(path[, connectListener])
`80` or `21`.
### socket.bytesRead A factory function, which returns a new unix
['net.Socket'](#net_class_net_socket) and automatically connects to the
supplied `path`.
The amount of received bytes. The `connectListener` parameter will be added as a listener for the
['connect'][] event once.
### socket.bytesWritten ## net.connect(port[, host][, connectListener])
The amount of bytes sent. A factory function, which returns a new
['net.Socket'](#net_class_net_socket) and automatically connects to the
supplied `port` and `host`.
If `host` is omitted, `'localhost'` will be assumed.
`net.Socket` instances are [EventEmitter][] with the following events: The `connectListener` parameter will be added as a listener for the
['connect'][] event once.
### Event: 'lookup' ## net.createConnection(options[, connectListener])
Emitted after resolving the hostname but before connecting. A factory function, which returns a new ['net.Socket'](#net_class_net_socket)
Not applicable to UNIX sockets. and automatically connects with the supplied `options`.
* `err` {Error | Null} The error object. See [dns.lookup()][]. The options are passed to both the ['net.Socket'](#net_class_net_socket)
* `address` {String} The IP address. constructor and the ['socket.connect'](#net_socket_connect_options_connectlistener)
* `family` {String | Null} The address type. See [dns.lookup()][]. method.
### Event: 'connect' The `connectListener` parameter will be added as a listener for the
['connect'][] event once.
Emitted when a socket connection is successfully established. Here is an example of a client of the previously described echo server:
See `connect()`.
### Event: 'data' var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('disconnected from server');
});
* {Buffer object} To connect on the socket `/tmp/echo.sock` the second line would just be
changed to
Emitted when data is received. The argument `data` will be a `Buffer` or var client = net.connect({path: '/tmp/echo.sock'});
`String`. Encoding of data is set by `socket.setEncoding()`.
(See the [Readable Stream][] section for more information.)
Note that the __data will be lost__ if there is no listener when a `Socket` ## net.createConnection(path[, connectListener])
emits a `'data'` event.
### Event: 'end' A factory function, which returns a new unix
['net.Socket'](#net_class_net_socket) and automatically connects to the
supplied `path`.
Emitted when the other end of the socket sends a FIN packet. The `connectListener` parameter will be added as a listener for the
['connect'][] event once.
By default (`allowHalfOpen == false`) the socket will destroy its file ## net.createConnection(port[, host][, connectListener])
descriptor once it has written out its pending write queue. However, by
setting `allowHalfOpen == true` the socket will not automatically `end()`
its side allowing the user to write arbitrary amounts of data, with the
caveat that the user is required to `end()` their side now.
A factory function, which returns a new
['net.Socket'](#net_class_net_socket) and automatically connects to the
supplied `port` and `host`.
### Event: 'timeout' If `host` is omitted, `'localhost'` will be assumed.
Emitted if the socket times out from inactivity. This is only to notify that The `connectListener` parameter will be added as a listener for the
the socket has been idle. The user must manually close the connection. ['connect'][] event once.
See also: `socket.setTimeout()` ## net.createServer([options][, connectionListener])
Creates a new server. The `connectionListener` argument is
automatically set as a listener for the ['connection'][] event.
### Event: 'drain' `options` is an object with the following defaults:
Emitted when the write buffer becomes empty. Can be used to throttle uploads. {
allowHalfOpen: false,
pauseOnConnect: false
}
See also: the return values of `socket.write()` If `allowHalfOpen` is `true`, then the socket won't automatically send a FIN
packet when the other end of the socket sends a FIN packet. The socket becomes
non-readable, but still writable. You should call the `end()` method explicitly.
See ['end'][] event for more information.
### Event: 'error' If `pauseOnConnect` is `true`, then the socket associated with each incoming
connection will be paused, and no data will be read from its handle. This allows
connections to be passed between processes without any data being read by the
original process. To begin reading data from a paused socket, call `resume()`.
* {Error object} Here is an example of an echo server which listens for connections
on port 8124:
Emitted when an error occurs. The `'close'` event will be called directly var net = require('net');
following this event. var server = net.createServer(function(c) { //'connection' listener
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});
### Event: 'close' Test this by using `telnet`:
* `had_error` {Boolean} `true` if the socket had a transmission error. telnet localhost 8124
Emitted once the socket is fully closed. The argument `had_error` is a boolean To listen on the socket `/tmp/echo.sock` the third line from the last would
which says if the socket was closed due to a transmission error. just be changed to
server.listen('/tmp/echo.sock', function() { //'listening' listener
Use `nc` to connect to a UNIX domain socket server:
nc -U /tmp/echo.sock
## net.isIP(input) ## net.isIP(input)

Loading…
Cancel
Save