Client

Client

new Client(urlopt, optionsopt)

Source:
Properties:
Name Type Description
url string

Server url

id string

Unique connection id assigned by the server. It will be accessible after handshake.

state Client.State

Connection state

Line client class.

Example
// Add line-client to your html document
<script src="./node_modules/line-socket/dist/client-web-globals.js"></script>

// For web browsers (consuming as a commonjs module)
const LineClient = require('line-socket/client-web');

// For node.js
const LineClient = require('line-socket/client-node');

// Usage
const client = new LineClient('ws://localhost:8080');
client.connect();
Parameters:
Name Type Attributes Description
url string <optional>

Server url, default: ws://localhost.

options Object <optional>

Options object.

Properties
Name Type Attributes Description
handshake Object <optional>

Handshake options

Properties
Name Type Attributes Description
timeout number <optional>

Handshake timeout duration in milliseconds. Default: 30000 (30 seconds).

payload any <optional>

Handshake payload that will be send to server.

responseTimeout number <optional>

This is the timeout for getting response from the server when using client.send() method. Default: 10000 (10 seconds). Note that this option is ineffective for client.sendWithoutResponse() method.

disconnectTimeout number <optional>

In some browsers, close frame is not fired immediately. This timeout is for starting close procedure even if close frame is not arrived. Default: 5000 (5 seconds).

pingInterval number <optional>

Pinging interval. Default: 20000 (20 seconds).

reconnect boolean <optional>

Whether try to reconnect server after unexpected disconnection, default true.

reconnectOptions Object <optional>

Reconnection options.

Properties
Name Type Attributes Description
initialDelay number <optional>

In milliseconds. Default: 1000 (1 second).

multiply number <optional>

Default: 1.5

maxDelay number <optional>

In milliseconds. Default: 30000

randomness number <optional>

Random delay multiplier. Default: 0.5

uptime boolean <optional>

Whether keep & calculate uptime, default false. If this option is not true, client.getUptime() returns undefined.

uptimeOptions Object <optional>

Uptime options.

Properties
Name Type Attributes Description
interval number <optional>

Uptime checking interval. In milliseconds. Default: 5000 (5 seconds).

window number <optional>

Uptime checking window length. In milliseconds. Default: 300000 (5 minutes)

followRedirections boolean <optional>

Attempt to follow 30X redirections. If this options is set, after a native websocket connection error, line will try to make a http request to server url. If it is success, final response url will be used as server after couple of connection attempts. Default: false

Extends

  • EventEmitterExtra

Members

(static, readonly) ErrorCode :string

Source:
Properties:
Name Type Description
INVALID_OPTIONS string

When constructing new Client(), this error could be thrown.

INVALID_JSON string

Indicates an error while json parsing/stringify.

HANDSHAKE_ERROR string

This error can be emitted in Client.Events.CONNECTING_ERROR event. It indicates an operational error during the handshake. If options.reconnect is true, the client will try to reconnect again.

HANDSHAKE_REJECTED string

This error can be emitted in Client.Events.CONNECTING_ERROR event. It indicates that server is explicitly rejected the handshake, which probably means client's handshake payload is not accepted by server.

MESSAGE_TIMEOUT string

This error can be seen in rejection of client.send() method. This means the message is reached to server but the timeout is exceeded.

MESSAGE_REJECTED string

This error can be seen in rejection of client.send() method, which again indicates that server is explicitly rejected the message.

MESSAGE_NOT_RESPONDED string

When the response of a message failed to send to server, this error will be emitted in Client.Event.ERROR event.

WEBSOCKET_ERROR string

This error is for native websocket errors. Native error is wrapped by LineError and can be accessible under err.payload.

DISCONNECT_TIMEOUT string

When disconnect timeout is exceed, this error will be emited in Client.Events.ERROR event. After this event, the disconnect procedure will be started forcefully.

PING_ERROR string

This error can be seen in rejection of client.ping() method. After this error, client will be disconnected.

DISCONNECTED string

This error indicates the action is prohibited because client is not in connected state or connection is closing.

Type:
  • string

(static, readonly) Event :string

Source:
Properties:
Name Type Description
CONNECTING string

_connecting

CONNECTING_ERROR string

_connecting_error

CONNECTED string

_connected

DISCONNECTING string

_disconnecting

DISCONNECTED string

_disconnected

ERROR string

_error

Type:
  • string

(static, readonly) State :string

Source:
Properties:
Name Type Description
READY string

ready

CONNECTING string

connecting

HANDSHAKING string

handshaking

CONNECTED string

connected

DISCONNECTING string

disconnecting

DISCONNECTED string

disconnected

Type:
  • string

Methods

(static) fetchResponseUrl()

Source:

Polyfill http request for node

connect() → {boolean}

Source:

Starts the connection procedure.

If server url is invalid or there is a security error, this method will throw Client.ErrorCode.WEBSOCKET_ERROR.

When procedure is started, Client.Event.CONNECTING event will be emitted.

If an error occured during connection or handshake, the client will emit Client.Event.CONNECTING_ERROR.

If connection is failed for some reason and options.reconnect is true. The client will retry to connect.

Example
client.connect();

client.on(Client.Event.CONNECTED, () => {
  console.log('Client connected.');
});

client.on(Client.Event.CONNECTING_ERROR, (err) => {
  console.log('Could not connect!', err);
});
Returns:
Type
boolean

disconnect(codeopt, reasonopt, opt_retryopt) → {boolean}

Source:

Gracefully closes the connection. This method can throw Client.ErrorCode.WEBSOCKET_ERROR if provided parameters are invalid. If websocket is not closed after options.disconnectTimeout ms, the client will start the disconnection procedure forcefully.

Example
client.disconnect();

client.on(Client.Event.DISCONNECTED, (e) => {
  console.log('Disconnected', e.code, e.reason);
});
Parameters:
Name Type Attributes Description
code number <optional>

A numeric value indicating the status code explaining why the connection is being closed. Must be between 1000-4999. Default is 1000.

reason any <optional>

A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters).

opt_retry boolean <optional>

Whether retry to connect after disconnection.

Returns:
Type
boolean

dispose() → {Promise}

Source:

Disposes the client.

Returns:
Type
Promise

getUptime() → (nullable) {number}

Source:

Calculates (connection) uptime for last options.uptime.window (default 5 minutes) with options.uptime.interval (default 5 seconds) interval. Returns a number between 0 and 1. If options.uptime is false, this method returns nothing.

Returns:
Type
number

ping() → {Promise}

Source:

Sends a ping message to server, if it's failed, the connection will be closed and will retry to connect again. Server and client ping each other automatically with an interval.

Returns:
Type
Promise

send(name, payloadopt, timeoutopt) → {Promise}

Source:

Sends a message to server with awaiting its response. This method returns a promise which resolves the payload parameter will be passed into message.resolve(...) in server-side.

If server rejects the message with message.reject(...), this promise will be rejected with Client.ErrorCode.MESSAGE_REJECTED. You can access the original error object with err.payload.

Rejections:

  • Client.ErrorCode.INVALID_JSON: Could not stringify the message payload. Probably circular json.
  • Client.ErrorCode.MESSAGE_REJECTED: Message is explicitly rejected by the server.
  • Client.ErrorCode.MESSAGE_TIMEOUT: Message response did not arrived, timeout exceeded.
  • Client.ErrorCode.DISCONNECTED: Client is not connected or connection is closing
  • Client.ErrorCode.WEBSOCKET_ERROR: Native websocket error (INVALID_STATE_ERR or SYNTAX_ERR)
Example
client
  .send('hello', {some: 'payload'})
  .then((data) => {
    console.log('Sent and got the response', data);
  })
  .catch((err) => {
    if (err.code == Client.ErrorCode.MESSAGE_REJECTED) {
      console.log('Message rejected by server', err.payload);
    } else if (err.code == Client.ErrorCode.MESSAGE_TIMEOUT) {
      console.log('Server did not responded, timeout exceeded');
    } else {
      console.log('Could not send message', err);
    }
  });
Parameters:
Name Type Attributes Description
name string

Message name.

payload any <optional>

Optional message payload.

timeout number <optional>

Timeout duration for waiting the response. If this parameter is not provided, options.responseTimeout will be used.

Returns:
Type
Promise

sendWithoutResponse(name, payloadopt) → {Promise}

Source:

Sends a message to server without waiting its response. This method returns a promise that resolves with nothing if the message is successfully sent.

Rejections:

  • Client.ErrorCode.INVALID_JSON: Could not stringify the message payload. Probably circular json.
  • Client.ErrorCode.DISCONNECTED: Client is not connected or connection is closing
  • Client.ErrorCode.WEBSOCKET_ERROR: Native websocket error (INVALID_STATE_ERR or SYNTAX_ERR)
Example
client
  .sendWithoutResponse('hello', {some: data})
  .then(() => {
    console.log('Message is sent');
  })
  .catch((err) => {
    console.log('Could not send message');
  });
Parameters:
Name Type Attributes Description
name string
payload any <optional>
Returns:
Type
Promise