Browse Source

Rename net.Stream to net.Socket

v0.7.4-release
Ryan Dahl 14 years ago
parent
commit
b62152bc84
  1. 114
      doc/api/net.markdown
  2. 88
      lib/net.js

114
doc/api/net.markdown

@ -11,8 +11,8 @@ automatically set as a listener for the `'connection'` event.
### net.createConnection(arguments...) ### net.createConnection(arguments...)
Construct a new stream object and opens a stream to the given location. When Construct a new socket object and opens a socket to the given location. When
the stream is established the `'connect'` event will be emitted. the socket is established the `'connect'` event will be emitted.
The arguments for this method change the type of connection: The arguments for this method change the type of connection:
@ -131,10 +131,10 @@ The number of concurrent connections on the server.
#### Event: 'connection' #### Event: 'connection'
`function (stream) {}` `function (socket) {}`
Emitted when a new connection is made. `stream` is an instance of Emitted when a new connection is made. `socket` is an instance of
`net.Stream`. `net.Socket`.
#### Event: 'close' #### Event: 'close'
@ -144,29 +144,29 @@ Emitted when the server closes.
--- ---
### net.Stream ### net.Socket
This object is an abstraction of of a TCP or UNIX socket. `net.Stream` This object is an abstraction of of a TCP or UNIX socket. `net.Socket`
instance implement a duplex stream interface. They can be created by the instances implement a duplex Stream interface. They can be created by the
user and used as a client (with `connect()`) or they can be created by Node user and used as a client (with `connect()`) or they can be created by Node
and passed to the user through the `'connection'` event of a server. and passed to the user through the `'connection'` event of a server.
`net.Stream` instances are EventEmitters with the following events: `net.Socket` instances are EventEmitters with the following events:
#### stream.connect(port, [host], [callback]) #### socket.connect(port, [host], [callback])
#### stream.connect(path, [callback]) #### socket.connect(path, [callback])
Opens the connection for a given stream. If `port` and `host` are given, Opens the connection for a given socket. If `port` and `host` are given,
then the stream will be opened as a TCP stream, if `host` is omitted, then the socket will be opened as a TCP socket, if `host` is omitted,
`localhost` will be assumed. If a `path` is given, the stream will be `localhost` will be assumed. If a `path` is given, the socket will be
opened as a unix socket to that path. opened as a unix socket to that path.
Normally this method is not needed, as `net.createConnection` opens the Normally this method is not needed, as `net.createConnection` opens the
stream. Use this only if you are implementing a custom Stream or if a socket. Use this only if you are implementing a custom Socket or if a
Stream is closed and you want to reuse it to connect to another server. Socket is closed and you want to reuse it to connect to another server.
This function is asynchronous. When the `'connect'` event is emitted the This function is asynchronous. When the `'connect'` event is emitted the
stream is established. If there is a problem connecting, the `'connect'` socket is established. If there is a problem connecting, the `'connect'`
event will not be emitted, the `'error'` event will be emitted with event will not be emitted, the `'error'` event will be emitted with
the exception. the exception.
@ -174,34 +174,34 @@ The `callback` paramenter will be added as an listener for the 'connect'
event. event.
#### stream.setEncoding(encoding=null) #### socket.setEncoding(encoding=null)
Sets the encoding (either `'ascii'`, `'utf8'`, or `'base64'`) for data that is Sets the encoding (either `'ascii'`, `'utf8'`, or `'base64'`) for data that is
received. received.
#### stream.setSecure([credentials]) #### socket.setSecure([credentials])
Enables SSL support for the stream, with the crypto module credentials specifying Enables SSL support for the socket, with the crypto module credentials specifying
the private key and certificate of the stream, and optionally the CA certificates the private key and certificate of the socket, and optionally the CA certificates
for use in peer authentication. for use in peer authentication.
If the credentials hold one ore more CA certificates, then the stream will request If the credentials hold one ore more CA certificates, then the socket will request
for the peer to submit a client certificate as part of the SSL connection handshake. for the peer to submit a client certificate as part of the SSL connection handshake.
The validity and content of this can be accessed via `verifyPeer()` and `getPeerCertificate()`. The validity and content of this can be accessed via `verifyPeer()` and `getPeerCertificate()`.
#### stream.verifyPeer() #### socket.verifyPeer()
Returns true or false depending on the validity of the peers's certificate in the Returns true or false depending on the validity of the peers's certificate in the
context of the defined or default list of trusted CA certificates. context of the defined or default list of trusted CA certificates.
#### stream.getPeerCertificate() #### socket.getPeerCertificate()
Returns a JSON structure detailing the peer's certificate, containing a dictionary Returns a JSON structure detailing the peer's certificate, containing a dictionary
with keys for the certificate `'subject'`, `'issuer'`, `'valid_from'` and `'valid_to'`. with keys for the certificate `'subject'`, `'issuer'`, `'valid_from'` and `'valid_to'`.
#### stream.write(data, [encoding], [callback]) #### socket.write(data, [encoding], [callback])
Sends data on the stream. The second parameter specifies the encoding in the Sends data on the socket. The second parameter specifies the encoding in the
case of a string--it defaults to UTF8 encoding. case of a string--it defaults to UTF8 encoding.
Returns `true` if the entire data was flushed successfully to the kernel Returns `true` if the entire data was flushed successfully to the kernel
@ -211,62 +211,62 @@ buffer. Returns `false` if all or part of the data was queued in user memory.
The optional `callback` parameter will be executed when the data is finally The optional `callback` parameter will be executed when the data is finally
written out - this may not be immediately. written out - this may not be immediately.
#### stream.write(data, [encoding], [fileDescriptor], [callback]) #### socket.write(data, [encoding], [fileDescriptor], [callback])
For UNIX sockets, it is possible to send a file descriptor through the For UNIX sockets, it is possible to send a file descriptor through the
stream. Simply add the `fileDescriptor` argument and listen for the `'fd'` socket. Simply add the `fileDescriptor` argument and listen for the `'fd'`
event on the other end. event on the other end.
#### stream.end([data], [encoding]) #### socket.end([data], [encoding])
Half-closes the stream. I.E., it sends a FIN packet. It is possible the Half-closes the socket. I.E., it sends a FIN packet. It is possible the
server will still send some data. server will still send some data.
If `data` is specified, it is equivalent to calling `stream.write(data, encoding)` If `data` is specified, it is equivalent to calling `socket.write(data, encoding)`
followed by `stream.end()`. followed by `socket.end()`.
#### stream.destroy() #### socket.destroy()
Ensures that no more I/O activity happens on this stream. Only necessary in Ensures that no more I/O activity happens on this socket. Only necessary in
case of errors (parse error or so). case of errors (parse error or so).
#### stream.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.
#### stream.resume() #### socket.resume()
Resumes reading after a call to `pause()`. Resumes reading after a call to `pause()`.
#### stream.setTimeout(timeout) #### socket.setTimeout(timeout)
Sets the stream to timeout after `timeout` milliseconds of inactivity on Sets the socket to timeout after `timeout` milliseconds of inactivity on
the stream. By default `net.Stream` do not have a timeout. the socket. By default `net.Socket` do not have a timeout.
When an idle timeout is triggered the stream will receive 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()` event but the connection will not be severed. The user must manually `end()`
or `destroy()` the stream. or `destroy()` the socket.
If `timeout` is 0, then the existing idle timeout is disabled. If `timeout` is 0, then the existing idle timeout is disabled.
#### stream.setNoDelay(noDelay=true) #### socket.setNoDelay(noDelay=true)
Disables the Nagle algorithm. By default TCP connections use the Nagle Disables the Nagle algorithm. By default TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting `noDelay` will algorithm, they buffer data before sending it off. Setting `noDelay` will
immediately fire off data each time `stream.write()` is called. immediately fire off data each time `socket.write()` is called.
#### stream.setKeepAlive(enable=false, [initialDelay]) #### socket.setKeepAlive(enable=false, [initialDelay])
Enable/disable keep-alive functionality, and optionally set the initial Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle stream. delay before the first keepalive probe is sent on an idle socket.
Set `initialDelay` (in milliseconds) to set the delay between the last Set `initialDelay` (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0 for data packet received and the first keepalive probe. Setting 0 for
initialDelay will leave the value unchanged from the default initialDelay will leave the value unchanged from the default
(or previous) setting. (or previous) setting.
#### stream.remoteAddress #### socket.remoteAddress
The string representation of the remote IP address. For example, The string representation of the remote IP address. For example,
`'74.125.127.100'` or `'2001:4860:a005::68'`. `'74.125.127.100'` or `'2001:4860:a005::68'`.
@ -278,7 +278,7 @@ This member is only present in server-side connections.
`function () { }` `function () { }`
Emitted when a stream connection successfully is established. Emitted when a socket connection successfully is established.
See `connect()`. See `connect()`.
#### Event: 'data' #### Event: 'data'
@ -286,18 +286,18 @@ See `connect()`.
`function (data) { }` `function (data) { }`
Emitted when data is received. The argument `data` will be a `Buffer` or Emitted when data is received. The argument `data` will be a `Buffer` or
`String`. Encoding of data is set by `stream.setEncoding()`. `String`. Encoding of data is set by `socket.setEncoding()`.
(See the section on `Readable Stream` for more information.) (See the section on `Readable Socket` for more information.)
#### Event: 'end' #### Event: 'end'
`function () { }` `function () { }`
Emitted when the other end of the stream sends a FIN packet. Emitted when the other end of the socket sends a FIN packet.
By default (`allowHalfOpen == false`) the stream will destroy its file By default (`allowHalfOpen == false`) the socket will destroy its file
descriptor once it has written out its pending write queue. However, by descriptor once it has written out its pending write queue. However, by
setting `allowHalfOpen == true` the stream will not automatically `end()` setting `allowHalfOpen == true` the socket will not automatically `end()`
its side allowing the user to write arbitrary amounts of data, with the its side allowing the user to write arbitrary amounts of data, with the
caveat that the user is required to `end()` their side now. caveat that the user is required to `end()` their side now.
@ -306,10 +306,10 @@ caveat that the user is required to `end()` their side now.
`function () { }` `function () { }`
Emitted if the stream times out from inactivity. This is only to notify that Emitted if the socket times out from inactivity. This is only to notify that
the stream has been idle. The user must manually close the connection. the socket has been idle. The user must manually close the connection.
See also: `stream.setTimeout()` See also: `socket.setTimeout()`
#### Event: 'drain' #### Event: 'drain'
@ -329,8 +329,8 @@ following this event.
`function (had_error) { }` `function (had_error) { }`
Emitted once the stream is fully closed. The argument `had_error` is a boolean Emitted once the socket is fully closed. The argument `had_error` is a boolean
which says if the stream was closed due to a transmission error. which says if the socket was closed due to a transmission error.
--- ---

88
lib/net.js

@ -167,7 +167,7 @@ function onWritable(readable, writable) {
} }
} }
function initStream(self) { function initSocket(self) {
self._readWatcher = ioWatchers.alloc(); self._readWatcher = ioWatchers.alloc();
self._readWatcher.socket = self; self._readWatcher.socket = self;
self._readWatcher.callback = onReadable; self._readWatcher.callback = onReadable;
@ -185,10 +185,10 @@ function initStream(self) {
self.writable = false; self.writable = false;
} }
// Deprecated API: Stream(fd, type) // Deprecated API: Socket(fd, type)
// New API: Stream({ fd: 10, type: 'unix', allowHalfOpen: true }) // New API: Socket({ fd: 10, type: 'unix', allowHalfOpen: true })
function Stream(options) { function Socket(options) {
if (!(this instanceof Stream)) return new Stream(arguments[0], arguments[1]); if (!(this instanceof Socket)) return new Socket(arguments[0], arguments[1]);
stream.Stream.call(this); stream.Stream.call(this);
this.fd = null; this.fd = null;
@ -210,17 +210,19 @@ function Stream(options) {
setImplmentationMethods(this); setImplmentationMethods(this);
} }
} }
util.inherits(Stream, stream.Stream); util.inherits(Socket, stream.Stream);
exports.Stream = Stream; exports.Socket = Socket;
// Legacy naming.
exports.Stream = Socket;
Stream.prototype._onTimeout = function() { Socket.prototype._onTimeout = function() {
this.emit('timeout'); this.emit('timeout');
}; };
Stream.prototype.open = function(fd, type) { Socket.prototype.open = function(fd, type) {
initStream(this); initSocket(this);
this.fd = fd; this.fd = fd;
this.type = type || null; this.type = type || null;
@ -234,13 +236,13 @@ Stream.prototype.open = function(fd, type) {
exports.createConnection = function(port, host) { exports.createConnection = function(port, host) {
var s = new Stream(); var s = new Socket();
s.connect(port, host); s.connect(port, host);
return s; return s;
}; };
Object.defineProperty(Stream.prototype, 'readyState', { Object.defineProperty(Socket.prototype, 'readyState', {
get: function() { get: function() {
if (this._connecting) { if (this._connecting) {
return 'opening'; return 'opening';
@ -264,7 +266,7 @@ Object.defineProperty(Stream.prototype, 'readyState', {
// Returns true if all the data was flushed to socket. Returns false if // Returns true if all the data was flushed to socket. Returns false if
// something was queued. If data was queued, then the 'drain' event will // something was queued. If data was queued, then the 'drain' event will
// signal when it has been finally flushed to socket. // signal when it has been finally flushed to socket.
Stream.prototype.write = function(data /* [encoding], [fd], [cb] */) { Socket.prototype.write = function(data /* [encoding], [fd], [cb] */) {
var encoding, fd, cb; var encoding, fd, cb;
// parse arguments // parse arguments
@ -301,7 +303,7 @@ Stream.prototype.write = function(data /* [encoding], [fd], [cb] */) {
// Slow. There is already a write queue, so let's append to it. // Slow. There is already a write queue, so let's append to it.
if (this._writeQueueLast() === END_OF_FILE) { if (this._writeQueueLast() === END_OF_FILE) {
throw new Error('Stream.end() called already; cannot write.'); throw new Error('Socket.end() called already; cannot write.');
} }
var last = this._writeQueue.length - 1; var last = this._writeQueue.length - 1;
@ -351,9 +353,9 @@ Stream.prototype.write = function(data /* [encoding], [fd], [cb] */) {
// 2. Write data to socket. Return true if flushed. // 2. Write data to socket. Return true if flushed.
// 3. Slice out remaining // 3. Slice out remaining
// 4. Unshift remaining onto _writeQueue. Return false. // 4. Unshift remaining onto _writeQueue. Return false.
Stream.prototype._writeOut = function(data, encoding, fd, cb) { Socket.prototype._writeOut = function(data, encoding, fd, cb) {
if (!this.writable) { if (!this.writable) {
throw new Error('Stream is not writable'); throw new Error('Socket is not writable');
} }
var buffer, off, len; var buffer, off, len;
@ -445,7 +447,7 @@ Stream.prototype._writeOut = function(data, encoding, fd, cb) {
leftOver.used = leftOver.length; // used the whole thing... leftOver.used = leftOver.length; // used the whole thing...
// util.error('data.used = ' + data.used); // util.error('data.used = ' + data.used);
//if (!this._writeQueue) initWriteStream(this); //if (!this._writeQueue) initWriteSocket(this);
// data should be the next thing to write. // data should be the next thing to write.
this._writeQueue.unshift(leftOver); this._writeQueue.unshift(leftOver);
@ -463,7 +465,7 @@ Stream.prototype._writeOut = function(data, encoding, fd, cb) {
// Flushes the write buffer out. // Flushes the write buffer out.
// Returns true if the entire buffer was flushed. // Returns true if the entire buffer was flushed.
Stream.prototype.flush = function() { Socket.prototype.flush = function() {
while (this._writeQueue && this._writeQueue.length) { while (this._writeQueue && this._writeQueue.length) {
var data = this._writeQueue.shift(); var data = this._writeQueue.shift();
var encoding = this._writeQueueEncoding.shift(); var encoding = this._writeQueueEncoding.shift();
@ -483,13 +485,13 @@ Stream.prototype.flush = function() {
}; };
Stream.prototype._writeQueueLast = function() { Socket.prototype._writeQueueLast = function() {
return this._writeQueue.length > 0 ? return this._writeQueue.length > 0 ?
this._writeQueue[this._writeQueue.length - 1] : null; this._writeQueue[this._writeQueue.length - 1] : null;
}; };
Stream.prototype.setEncoding = function(encoding) { Socket.prototype.setEncoding = function(encoding) {
var StringDecoder = require('string_decoder').StringDecoder; // lazy load var StringDecoder = require('string_decoder').StringDecoder; // lazy load
this._decoder = new StringDecoder(encoding); this._decoder = new StringDecoder(encoding);
}; };
@ -521,7 +523,7 @@ function doConnect(socket, port, host) {
function toPort(x) { return (x = Number(x)) >= 0 ? x : false; } function toPort(x) { return (x = Number(x)) >= 0 ? x : false; }
Stream.prototype._onConnect = function() { Socket.prototype._onConnect = function() {
var errno = socketError(this.fd); var errno = socketError(this.fd);
if (errno == 0) { if (errno == 0) {
// connection established // connection established
@ -548,8 +550,8 @@ Stream.prototype._onConnect = function() {
}; };
Stream.prototype._onWritable = function() { Socket.prototype._onWritable = function() {
// Stream becomes writable on connect() but don't flush if there's // Socket becomes writable on connect() but don't flush if there's
// nothing actually to write // nothing actually to write
if (this.flush()) { if (this.flush()) {
if (this._events && this._events['drain']) this.emit('drain'); if (this._events && this._events['drain']) this.emit('drain');
@ -559,7 +561,7 @@ Stream.prototype._onWritable = function() {
}; };
Stream.prototype._onReadable = function() { Socket.prototype._onReadable = function() {
var self = this; var self = this;
// If this is the first recv (pool doesn't exist) or we've used up // If this is the first recv (pool doesn't exist) or we've used up
@ -623,14 +625,14 @@ Stream.prototype._onReadable = function() {
}; };
// var stream = new Stream(); // var socket = new Socket();
// stream.connect(80) - TCP connect to port 80 on the localhost // socket.connect(80) - TCP connect to port 80 on the localhost
// stream.connect(80, 'nodejs.org') - TCP connect to port 80 on nodejs.org // socket.connect(80, 'nodejs.org') - TCP connect to port 80 on nodejs.org
// stream.connect('/tmp/socket') - UNIX connect to socket specified by path // socket.connect('/tmp/socket') - UNIX connect to socket specified by path
Stream.prototype.connect = function() { Socket.prototype.connect = function() {
var self = this; var self = this;
initStream(self); initSocket(self);
if (self.fd) throw new Error('Stream already opened'); if (self.fd) throw new Error('Socket already opened');
if (!self._readWatcher) throw new Error('No readWatcher'); if (!self._readWatcher) throw new Error('No readWatcher');
require('timers').active(socket); require('timers').active(socket);
@ -666,25 +668,25 @@ Stream.prototype.connect = function() {
}; };
Stream.prototype.address = function() { Socket.prototype.address = function() {
return getsockname(this.fd); return getsockname(this.fd);
}; };
Stream.prototype.setNoDelay = function(v) { Socket.prototype.setNoDelay = function(v) {
if ((this.type == 'tcp4') || (this.type == 'tcp6')) { if ((this.type == 'tcp4') || (this.type == 'tcp6')) {
setNoDelay(this.fd, v); setNoDelay(this.fd, v);
} }
}; };
Stream.prototype.setKeepAlive = function(enable, time) { Socket.prototype.setKeepAlive = function(enable, time) {
if ((this.type == 'tcp4') || (this.type == 'tcp6')) { if ((this.type == 'tcp4') || (this.type == 'tcp6')) {
var secondDelay = Math.ceil(time / 1000); var secondDelay = Math.ceil(time / 1000);
setKeepAlive(this.fd, enable, secondDelay); setKeepAlive(this.fd, enable, secondDelay);
} }
}; };
Stream.prototype.setTimeout = function(msecs) { Socket.prototype.setTimeout = function(msecs) {
if (msecs > 0) { if (msecs > 0) {
require('timers').enroll(this, msecs); require('timers').enroll(this, msecs);
if (this.fd) { require('timers').active(this); } if (this.fd) { require('timers').active(this); }
@ -694,13 +696,13 @@ Stream.prototype.setTimeout = function(msecs) {
}; };
Stream.prototype.pause = function() { Socket.prototype.pause = function() {
if (this._readWatcher) this._readWatcher.stop(); if (this._readWatcher) this._readWatcher.stop();
}; };
Stream.prototype.resume = function() { Socket.prototype.resume = function() {
if (this.fd === null) throw new Error('Cannot resume() closed Stream.'); if (this.fd === null) throw new Error('Cannot resume() closed Socket.');
if (this._readWatcher) { if (this._readWatcher) {
this._readWatcher.stop(); this._readWatcher.stop();
this._readWatcher.set(this.fd, true, false); this._readWatcher.set(this.fd, true, false);
@ -708,7 +710,7 @@ Stream.prototype.resume = function() {
} }
}; };
Stream.prototype.destroySoon = function() { Socket.prototype.destroySoon = function() {
if (this.flush()) { if (this.flush()) {
this.destroy(); this.destroy();
} else { } else {
@ -716,7 +718,7 @@ Stream.prototype.destroySoon = function() {
} }
}; };
Stream.prototype.destroy = function(exception) { Socket.prototype.destroy = function(exception) {
// pool is shared between sockets, so don't need to free it here. // pool is shared between sockets, so don't need to free it here.
var self = this; var self = this;
@ -758,7 +760,7 @@ Stream.prototype.destroy = function(exception) {
}; };
Stream.prototype._shutdown = function() { Socket.prototype._shutdown = function() {
if (!this.writable) { if (!this.writable) {
throw new Error('The connection is not writable'); throw new Error('The connection is not writable');
} else { } else {
@ -780,7 +782,7 @@ Stream.prototype._shutdown = function() {
}; };
Stream.prototype.end = function(data, encoding) { Socket.prototype.end = function(data, encoding) {
if (this.writable) { if (this.writable) {
if (this._writeQueueLast() !== END_OF_FILE) { if (this._writeQueueLast() !== END_OF_FILE) {
if (data) this.write(data, encoding); if (data) this.write(data, encoding);
@ -855,7 +857,7 @@ function Server(/* [ options, ] listener */) {
var options = { fd: peerInfo.fd, var options = { fd: peerInfo.fd,
type: self.type, type: self.type,
allowHalfOpen: self.allowHalfOpen }; allowHalfOpen: self.allowHalfOpen };
var s = new Stream(options); var s = new Socket(options);
s.remoteAddress = peerInfo.address; s.remoteAddress = peerInfo.address;
s.remotePort = peerInfo.port; s.remotePort = peerInfo.port;
s.type = self.type; s.type = self.type;

Loading…
Cancel
Save