Recent Changes - Search:

edit SideBar

socket Module

Module supporting TCP sockets. This module defines three classes, SocketClient, SocketServer, and Socket.

To establish a connection, create an instance of SocketServer and listen for connection events. When a connection request comes in, the listener will be passed an instance of Socket. The server can send data through that instance and listen for incoming data events.

On another machine (or the same machine), create an instance of SocketClient. When the connection is established to the server, this instance will emit an 'open' event. When data arrives from the server, it will emit a 'data' event. You can invoke send() to send data to the server.

The send() function can accept data in many different forms. You can send a string, an image, a number, or an array of numbers. Two utility functions supportedReceiveTypes() and supportedSendTypes() tell you exactly which data types supported by the host. Arrays of numeric types are also supported.

If the rawBytes option is true (the default), then data is sent without any message framing. As a consequence, the recipient of the data may emit only a portion of any sent data, or it may even coalesce data provided in separate invocations of send(). If rawBytes is false, then messages will be framed so that each invocation of send() results in exactly one data item emitted at the other end. This will only work if both sides of the connection implement the same framing protocol, e.g. if they both are implemented with this same module. To communicate with external tools that do not support this message framing protocol, leave rawBytes set to true.

The message framing protocol used here is very simple. Each message is preceded by one byte indicating the length of the message. If the message has length greater than 254, then the value of this byte will be 255 and the subsequent four bytes will represent the length of the message. The message then follows these bytes.

Functions

  • supportedReceiveTypes(): Return an array of the types that can be received over the socket supported by the current host.
  • supportedSendTypes(): Return an array of the types that can be received over the socket supported by the current host.

SocketClient Class

An instance of this class, created with new, is a socket client that can send or receive messages to a server at the host and port to the constructor. The constructor takes three arguments:

  • port: The remote port to connect to (the default is 4000).
  • host: The remote host to connect to (the default is 'localhost').
  • options: The options (the default options are specified below).

The instance of SocketClient provides the following functions:

  • send(data): Send data over the socket. If the socket has not yet been successfully opened, then queue data to be sent later, when the socket is opened, unless discardMessagesBeforeOpen is true.
  • close(): Close the current connection with the server. This will indicate to the server that no more data will be sent, but data may still be received from the server.
  • open(): Open the connection. Call this after setting up event handlers.

This class subclasses EventEmitter and emits the following events:

  • open: Emitted with no arguments when the socket has been successfully opened.
  • data: Emitted with the data as an argument when data arrives on the socket.
  • close: Emitted with no arguments when the socket is closed.
  • error: Emitted with an error message when an error occurs.

You can invoke the send() function of this SocketClient object to send data to the server. If the socket is not opened yet, then data will be discarded or queued to be sent later, depending on the value of the discardMessagesBeforeOpen option (which defaults to false).

The event close will be emitted when the socket is closed, and error if an an error occurs (with an error message as an argument).

A simple example that sends a message, and closes the socket on receiving a reply:

    var socket = require('socket');
    var client = new socket.SocketClient();
    client.on('open', function() {
        client.send('hello world');
    });
    client.on('data', function onData(data) {
        print('Received from socket: ' + data);
        client.close();
    });
    client.open();

The options argument is a JSON object that can include:

  • connectTimeout: The time to wait (in milliseconds) before declaring a connection attempt to have failed.
  • idleTimeout: The amount of idle time in seconds that will cause a disconnection of a socket. This defaults to 0, which means no timeout.
  • discardMessagesBeforeOpen: If true, then discard any messages passed to SocketClient.send() before the socket is opened. If false, then queue the messages to be sent when the socket opens. This defaults to false.
  • keepAlive: Whether to keep a connection alive and reuse it. This defaults to true.
  • maxUnsentMessages: The maximum number of unsent messages to queue before further calls to send() will fail. A value of 0 means no limit. This defaults to 100.
  • noDelay: If true, data as sent as soon as it is available (the default). If false, data may be accumulated until a reasonable packet size is formed in order to make more efficient use of the network (using Nagle's algorithm).
  • rawBytes: If true (the default), then transmit only the data bytes provided to send() without any header. If false, then prepend sent data with length information and assume receive data starts with length information. Setting this false on both ends will ensure that each data item passed to send() is emitted once in its entirety at the receiving end, as a single message. When this is false, the receiving end can emit a partially received message or could concatenate two messages and emit them together.
  • receiveBufferSize: The size of the receive buffer. Defaults to 65536.
  • receiveType: See below.
  • reconnectAttempts: The number of times to try to reconnect. If this is greater than 0, then a failure to attempt will trigger additional attempts. This defaults to 10.
  • reconnectInterval: The time between reconnect attempts, in milliseconds. This defaults to 100.
  • sendBufferSize: The size of the receive buffer. Defaults to 65536.
  • sendType: See below.
  • sslTls: Whether SSL/TLS is enabled. This defaults to false.
  • trustAll: Whether to trust servers. This defaults to false. Setting it to true means that if sslTls is set to true, then any certificate provided by the server will be trusted. FIXME: Need to provide a trusted list if this is false.

The send and receive types can be any of those returned by supportedReceiveTypes() and supportedSendTypes(), respectively. If both ends of the socket are known to be JavaScript clients, then you should use the 'number' data type for numeric data. If one end or the other is not JavaScript, then you can use more specified types such as 'float' or 'int', if they are supported by the host. In all cases, received numeric data will be converted to JavaScript 'number' when emitted. For sent data, this will try to convert a JavaScript number to the specified type. The type 'number' is equivalent to 'double'.

When type conversions are needed, e.g. when you send a double with sendType set to int, or an int with sendType set to byte, then a "primitive narrowing conversion" will be applied.

For numeric types, you can also send an array with a single call to send(). The elements of the array will be sent in sequence all at once, and may be received in one batch. If both ends have rawBytes set to false (specifying message framing), then these elements will be emitted at the receiving end all at once in a single array. Otherwise, they will be emitted one at a time.

For strings, you can also send an array of strings in a single call, but these will be simply be concatenated and received as a single string.

If the rawBytes option is set to false, then each data item passed to send(), of any type or array of types, will be coalesced into a single message and the receiving end (if it also has rawBytes set to false) will emit the entire message, and only the message, exactly once. Otherwise, a message may get fragmented, emitted in pieces, or coalesced with subsequent messages.

SocketServer Class

An instance of this class, created with new, is a socket server that can send or receive messages from a client. The client initiates the connection. The constructor takes one argument:

  • options: The options (the default options are specified below).

The instance of SocketServer provides the following function:

  • stop(): Stop the server and close all connections.
  • start(): Start the server. Call this after setting up event handlers.

An instance of a socket server that listens for connection requests and opens sockets when it receives them. This class is an event emitter that emits the following events:

  • listening: Emitted when the server is listening. This will be passed the port number that the server is listening on (this is useful if the port is specified to be 0).
  • connection: Emitted when a new connection is established after a request from (possibly remote) client. This will be passed an instance of a Socket class that can be used to send data or to close the socket. The instance of Socket is also an event emitter that emits 'close', 'data', and 'error' events.
  • error: Emitted if the server fails to start listening. This will be passed an error message.

A typical usage pattern looks like this:

   var server = new socket.SocketServer();
   server.on('listening', function(port) {
       console.log('Server listening on port: ' + port);
   });
   var connectionCount = 0;
   server.on('connection', function(serverSocket) {
       var connectionNumber = connectionCount++;
       console.log('Server connected on a new socket number: ' + connectionNumber);
       serverSocket.on('data', function(data) {
           console.log('Server received data on connection '
                   + connectionNumber
                   + ": "
                   + data);
       });
   });
   server.start();

When the connection event is emitted, it will be passed a Socket object, defined below, which has a send() function. For example, to send a reply to each incoming message, replace the above data handler as follows:

   serverSocket.on('data', function(data) {
      socket.send('Reply message');
   });

The Socket object also has a close() function that allows the server to close the individual connection without stopping the server. The SocketServer object has a stop() function that will close all connections and shut down the server.

An options argument can be passed to the SocketServer constructor above. This is a JSON object containing the following optional fields:

  • clientAuth: One of 'none', 'request', or 'required', meaning whether it requires that a certificate be presented.
  • hostInterface: The name of the network interface to use for listening, e.g. 'localhost'. The default is '0.0.0.0', which means to listen on all available interfaces.
  • idleTimeout: The amount of idle time in seconds that will cause a disconnection of a socket. This defaults to 0, which means no timeout.
  • keepAlive: Whether to keep a connection alive and reuse it. This defaults to true.
  • keyStorePassword: If sslTls is set to true, then this option needs to specify the password for the key store specified by keyStorePath.
  • keyStorePath: If sslTls is set to true, then this option needs to specify the fully qualified filename for the file that stores the certificate that this server will use to identify itself. This path can be any of those understood by the Ptolemy host, e.g. paths beginning with $CLASSPATH/.
  • noDelay: If true, data as sent as soon as it is available (the default). If false, data may be accumulated until a reasonable packet size is formed in order to make more efficient use of the network (using Nagle's algorithm).
  • port: The default port to listen on. This defaults to 4000. a value of 0 means to choose a random ephemeral free port.
  • rawBytes: If true (the default), then transmit only the data bytes provided to send() without any header. If false, then prepend sent data with length information and assume receive data starts with length information. Setting this false on both ends will ensure that each data item passed to send() is emitted once in its entirety at the receiving end, as a single message. When this is false, the receiving end can emit a partially received message or could concatenate two messages and emit them together.
  • receiveBufferSize: The size of the receive buffer. Defaults to 65536.
  • receiveType: See below.
  • sendBufferSize: The size of the receive buffer. Defaults to 65536.
  • sendType: See below.
  • sslTls: Whether SSL/TLS is enabled. This defaults to false.

The send and receive types can be any of those returned by supportedReceiveTypes() and supportedSendTypes(), respectively, defined above. If both ends of the socket are known to be JavaScript clients, then you should use the 'number' data type for numeric data. If one end or the other is not JavaScript, then you can use more specified types such as 'float' or 'int', if they are supported by the host. In all cases, received numeric data will be converted to JavaScript 'number' when emitted. For sent data, this will try to convert a JavaScript number to the specified type. The type 'number' is equivalent to 'double'.

When type conversions are needed, e.g. when you send a double with sendType set to int, or an int with sendType set to byte, then a "primitive narrowing conversion" will be applied.

For numeric types, you can also send an array with a single call to send(). The elements of the array will be sent in sequence all at once, and may be received in one batch. If both ends have rawBytes set to false (specifying message framing), then these elements will be emitted at the receiving end all at once in a single array. Otherwise, they will be emitted one at a time.

For strings, you can also send an array of strings in a single call, but these will be simply be concatenated and received as a single string.

Socket Class

An instance of this class is created by the SocketServer whenever a new socket connection has been established. That instance is emitted as an argument to the connection event. An instance of Socket is an event emitter that emits the following events:

  • data: Emitted when data is received on any socket handled by this server. This will be passed the data.
  • close: Emitted when a socket is closed. This is not passed any arguments.
  • error: Emitted when an error occurs. This will be passed an error message.

An instance of this class provides the following functions:

  • close(): Close the socket. This will indicate to the client that the server will be sending no more data.
  • remoteHost(): Return the remote host IP address of this socket (a string).
  • remotePort(): Return the remote port of this socket (a number).
  • send(data): Send data over the socket.

Back to Optional JavaScript Modules

Edit - History - Print - Recent Changes - Search
Page last modified on July 20, 2016, at 12:37 pm