npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

xrtlibrary-tcputilities

v1.0.12

Published

TCP utilities module of XRT library.

Downloads

61

Readme

XRTLibrary-TCPUtilities

Introduction

A module that can help you write TCP client/server programs with synchronous-like style.

In practice, it is really hard (and expensive) to handle TCP connection correctly and effectively with the event-driven mechanism of the "net" module (many events have to be handled correctly and a state machine may also be needed in some situations).

This module helps you handle these situations correctly and write programs effectively with synchronous-like programming style which is like what you use in Python "socket" module.

Here is a sample client program:

let client = null;
try {
    //  Connect to the server.
    let clientConnectOpt = new TCPConnectOption(SERVER_HOST, SERVER_PORT);
    client = await TCPConnect(clientConnectOpt);

    //  Get bidirectional streams.
    let rs = client.getReadStream();
    let ws = client.getWriteStream();

    //  Send the request.
    await ws.writeAwaitable(Buffer.from("Hello message."));

    //  Read the response.
    let response = await rs.read(8);
    console.log("Result: " + response.toString());

    //  Close the connection.
    client.close();
    await client.whenClosed();
} finally {
    //  Clean up the connection.
    if (client !== null && !client.isClosed()) {
        client.close(true);
        await client.whenClosed();
        client = null;
    }
}

Installation

To install this package, you can use NPM by typing following command:

npm install xrtlibrary-tcputilities --save

Then you can import this library in your JavaScript code:

const XRTLibTCPUtilities = require("xrtlibrary-tcputilities");

Examples

Download this package and see the "examples" directory.

APIs

(Module) Error

TCP errors.

(Class) TCPError

TCP error.

Extend(s):

  • Error

(Class) TCPTimeoutError

TCP timeout error.

Extend(s):

  • TCPError

(Class) TCPEndOfStreamError

TCP end of stream error.

Extend(s):

  • TCPError

(Class) TCPOperationCancelledError

TCP operation cancelled error.

Extend(s):

  • TCPError

(Class) TCPInvalidOperationError

TCP invalid operation error.

Extend(s):

  • TCPError

(Class) TCPAddressAlreadyInUseError

TCP address already in use error.

Extend(s):

  • TCPError

(Class) TCPAddressNotAvailableError

TCP address not available error.

Extend(s):

  • TCPError

(Module) Client

TCP client.

(Class) TCPConnectOptionBase

Base class of all TCP connect option classes.

option.getConnectTimeout()

Get the connect timeout.

Return value:

  • (?Number) The timeout (> 0, NULL if not set).
option.setConnectTimeout(timeout)

Set the connect timeout.

Parameter(s):

  • timeout (?Number): The timeout (> 0, NULL if not set).
option.getIdleTimeout()

Get the idle timeout.

Return value:

  • (?Number) The timeout (> 0, NULL if not set).
option.setIdleTimeout(timeout)

Set the idle timeout.

Note(s):

  • The timeout would be applied to the connection automatically via the connection.setTimeout() interface (NULL is mapped to 0).

Parameter(s):

  • timeout (?Number): The timeout (> 0, NULL if not set).
option.isHalfOpen()

Get whether the TCP half-open flag was turned on.

Return value:

  • (Boolean) True if so.
option.setHalfOpen()

Set the TCP half-open flag.

Parameter(s):

  • enabled (Boolean): True if so.

(Class) TCPConnectOption

TCP connect option.

Extend(s):

  • TCPConnectOption
new TCPConnectOption(host, port)

Construct a new object.

Parameter(s):

  • host (String): The target host.
  • port (Number): The target port.
option.getIPStackVersion()

Get the IP stack version.

Return value:

  • (Number) The version (4 or 6).
option.setIPStackVersion(version)

Set the IP stack version.

Parameter(s):

  • version (Number): The version (4 or 6).
option.getDNSHints()

Get DNS lookup hints.

Reference(s):

Return value:

  • (Number) The hints.
option.setDNSHints(hints)

Set DNS lookup hints.

Reference(s):

Parameter(s):

  • hints (Number): The hints.
option.getHost()

Get the target host.

Return value:

  • (String) The host.
option.getPort()

Get the target port.

Return value:

  • (Number) The port.

(Class) TCPConnectOptionIPC

TCP connect option for IPC.

Extend(s):

  • TCPConnectOptionBase
new TCPConnectOptionIPC(path)

Construct a new object.

Parameter(s):

  • path (String): The IPC path.
option.getPath()

Get the IPC path.

Return value:

  • (String) The path.

TCPConnect(option, [cancellator])

Connect to TCP server.

Note(s):

  • Once you passed "option" object to this function, you should never change it externally again. Otherwise, unexpected behavior may occurred.

Exception(s):

  • Error.TCPTimeoutError: Raised when TCP connect timeouted.
  • Error.TCPError (including derived classes): Raised when other TCP error occurred.
  • Error.TCPOperationCancelled: Raised when the cancellator was activated.

Parameter(s):

  • option (TCPConnectOptionBase): The TCP connect option.
  • cancellator (ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • (Promise<TCPConnection>) The promise object (resolves with the TCP connection, rejects when error occurred).

(Module) Server

TCP server.

(Class) TCPListenOptionBase

Base class of TCP listen option classes.

option.isDualStackEnabled()

Get whether the dual-stack was enabled.

Return value:

  • (Boolean) True if so.
option.setDualStack(enabled)

Set the enablity of the dual-stack.

Parameter(s):

  • enabled (Boolean): True if enabled.
option.isPortExclusive()

Get whether the port exclusive was enabled.

Return value:

  • (Boolean) True if so.
option.setPortExclusive(enabled)

Set the enablity of the port exclusive.

Parameter(s):

  • enabled (Boolean): True if enabled.

(Class) TCPListenOption

TCP listen option.

Extend(s):

  • TCPListenOptionBase
new TCPListenOption(host, port)

Construct a new object.

Parameter(s):

  • host (String): The listen host.
  • port (Number): The listen port.
option.getHost()

Get the listen host.

Return value:

  • (String) The host.
option.getPort()

Get the listen port.

Return value:

  • (Number) The port.

(Class) TCPListenOptionIPC

TCP listen option for IPC.

Extend(s):

  • TCPListenOptionBase
new TCPListenOptionIPC(path)

Construct a new object.

Parameter(s):

  • path (String): The listen path.
option.getPath()

Get the listen path.

Return value:

  • (String) The path.
option.isReadableByAllUsers()

Get whether the pipe is readable for all users.

Return value:

  • (Boolean) True if so.
option.setReadableByAllUsers(enabled)

Set the pipe readablity for all users.

Parameter(s):

  • enabled (Boolean): True if readable.
option.isWritableByAllUsers()

Get whether the pipe is writable for all users.

Return value:

  • (Boolean) True if so.
option.setWritableByAllUsers(enabled)

Set the pipe writablity for all users.

Parameter(s):

  • enabled (Boolean): True if writable.

(Class) TCPServerOption

TCP server option.

new TCPServerOption()

Construct a new object.

option.isHalfOpen()

Get whether the TCP half-open flag was turned on.

Return value:

  • (Boolean) True if so.
option.setHalfOpen(enabled)

Set the TCP half-open flag.

Parameter(s):

  • enabled (Boolean): True if so.
option.getMaxConnectionLimit()

Get the max connection limit.

Return value:

  • (?Number) The limit (NULL if not set).
option.setMaxConnectionLimit(limit)

Set the max connection limit.

Parameter(s):

  • limit (?Number): The new limit (NULL if not set).
option.getDropUnacceptedConnectionsTimeout()

Get the timeout of dropping unaccepted connections.

Return value:

  • (Number) The timeout (0 if not set).
option.setDropUnacceptedConnectionsTimeout(timeout)

Set the timeout of dropping unaccepted connections.

Parameter(s):

  • timeout (Number): The timeout (0 if not set).

(Class) TCPServer

TCP server.

new TCPServer(option)

Construct a new object.

Parameter(s):

  • option (TCPServerOption): The TCP server option.
server.accept([cancellator])

Accept a connection.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.
  • Error.TCPInvalidOperationError: Raised in (when) following situations:
    • The server is not listened yet.
    • The server was closed.

Parameter(s):

Return value:

  • (Promise<TCPConnection>) The promise object (resolves with the TCP connection object when succeed, rejects when error occurred).
server.listen(option)

Listen to specified endpoint.

Exception(s):

  • Error.TCPInvalidOperationError: Raised in (when) one of following situations:
    • The server was already closed.
    • The server was already listened.
    • Previous calling to listen() method is still in pending.
  • Error.TCPAddressAlreadyInUseError: Raised if the address was already in use.
  • Error.TCPAddressNotAvailableError: Raised if the address was not available.

Parameter(s):

  • option (TCPListenOptionBase): The listen option.

Return value:

  • (Promise<Object>) The promise object (resolves with the listen address when succeed, rejects when error occurred).
    • address (String): The listening address.
    • port (Number): The listening port.
    • family (String): The protocol family ("IPv4" or "IPv6").
server.isListened()

Get whether the server was listened.

Return value:

  • (Boolean) True if so.
server.whenListened([cancellator])

Wait for the server to be listened.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise<Object>) The promise object (resolves with the listen address when listened, rejects when cancelled).
    • address (String): The listening address.
    • port (Number): The listening port.
    • family (String): The protocol family ("IPv4" or "IPv6").
server.isErrorOccurred()

Get whether an error occurred.

Return value:

  • (Boolean) True if so.
server.whenError([cancellator])

Wait for error occurred.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise<Error>) The promise object (resolves with the error when error occurred, rejects when cancelled).
server.isClosing()

Get whether the server is closing.

Return value:

  • (Boolean) True if so.
server.isClosed()

Get whether the server is closed.

Return value:

  • (Boolean) True if so.
server.whenClosed([cancellator])

Wait for the server to be closed.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise) The promise object (resolves when server closed, rejects when cancelled).
server.close([forcibly])

Close the server.

Exception(s):

  • Error.TCPInvalidOperationError: Raised when the server was already closed.

Parameter(s):

  • forcibly (Boolean): (Optional) True if the server should be closed forcibly.

(Constant) TCPSTREAM_READPACKET

Indicates a packet is wanted.

(Class) TCPReadStream

rs.read(count, [cancellator])

Read from the stream.

Exception(s):

  • Error.TCPEndOfStreamError: Raised when the read stream was closed.
  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.
  • Error.TCPInvalidOperationError: Raised in one of following situation(s):
    • The "count" parameter is invalid.

Parameter(s):

  • count (Number): The count to be read (use TCPSTREAM_READPACKET if a packet is wanted).
  • cancellator (ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • (Promise<Buffer>) The promise object (resolves when succeed, rejects when cancelled or error occurred).

rs.readNoCopy(count, [bufferList], [partial], [cancellator])

Read from the stream with zero-copy mechanism.

Note(s):

  • Buffer that has been read would be pushed to the buffer list, the buffer list returned by this function is exactly the same as the one specified by the "bufferList" parameter.
  • If the buffer list specified is not empty, it would be cleared.
  • Zero-copy mechanism is used by this method to avoid data copying.
  • If the value of "partial" parameter is true, this method would return even when only partial data was available. Otherwise (by default), this method would wait until all bytes are available.

Exception(s):

  • Error.TCPEndOfStreamError: Raised when the read stream was closed.
  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.
  • Error.TCPInvalidOperationError: Raised in one of following situation(s):
    • The "count" parameter is invalid.

Parameter(s):

  • count (Number): The count to be read (use TCPSTREAM_READPACKET if a packet is wanted).
  • bufferList (Buffer[]): The buffer list.
  • partial (Boolean): True if partial data is allowed.
  • cancellator (ConditionalSynchronizer): (Optional) The cancellator.

Return value:

  • (Promise<Buffer[]>) The promise object (resolves with the buffer list when succeed, rejects when cancelled or error occurred).

rs.unread(data)

Unread data to the stream.

Parameter(s):

  • data (Buffer): The data.

rs.isAvailable([length])

Get whether there was data available to be read.

Parameter(s):

  • length (Number): The length of required data (default: 1).

Return value:

  • (Boolean) True if so.

rs.whenAvailable([cancellator])

Wait for data to be available.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise) The promise object (resolves if data was available, rejects if error occurred).

rs.isEnded()

Get whether the read stream was ended.

Return value:

  • (Boolean) True if so.

rs.whenEnded([cancellator])

Wait for the read stream to be ended.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise) The promise object (resolves when ended, rejects when cancelled).

(Class) TCPWriteStream

TCP write stream.

ws.write(data)

Write data to the stream.

Note(s):

  • This method wouldn't throw any error, it just wrote the data to the userspace buffer.

Parameter(s):

  • data (Buffer): The data.

ws.writeAwaitable(data, [cancellator])

Write data to the stream with an awaitable mechanism.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.
  • Error.TCPEndOfStreamError: Raised when the connection was closed before the data flushed to the kernel buffer successfully.

Parameter(s):

Return value:

  • (Promise) The promise object (resolves when the data flushed to kernel space, rejects when cancelled or error occurred).

ws.isFlushing()

Get whether the stream is flushing.

Return value:

  • (Boolean) True if so.

ws.end()

End the stream.

Exception(s):

  • Error.TCPInvalidOperationError: Raised when this method was called multiple times.

(Class) TCPConnection

TCP connection.

connection.getReadStream()

Get the read stream.

Return value:

  • (TCPReadStream) The stream.

connection.getWriteStream()

Get the write stream.

Return value:

  • (TCPWriteStream) The stream.

connection.getLocalAddressInformation()

Get local address information.

Note(s):

  • This method would return NULL until the connection was ready (connected).

Return value:

  • (?Object) The address information.
    • address (String): The local address.
    • port (Number): The local port.

connection.getRemoteAddressInformation()

Get remote address information.

Note(s):

  • This method would return NULL until the connection was ready (connected).

Return value:

  • (?Object) The address information.
    • address (String): The remote address.
    • port (Number): The remote port.
    • family (String): The protocol family.

connection.getUserspaceReceiveBufferSize()

Get the userspace receive buffer size.

Return value:

  • (Number) The buffer size.

connection.setUserspaceReceiveBufferSize(size)

Set the userspace receive buffer size.

Parameter(s):

  • size (Number): The new buffer size.

connection.getUserspaceSendBufferSize()

Get the userspace send buffer size.

Return value:

  • (Number) The buffer size.

connection.setUserspaceSendBufferSize(size)

Set the userspace send buffer size.

Parameter(s):

  • size (Number): The new buffer size.

connection.isKeepalive()

Get whether the TCP SO_KEEPALIVE option was enabled.

Return value:

  • (Boolean) True if so.

connection.setKeepalive(enabled, initialDelay)

Set the TCP SO_KEEPALIVE option.

Exception(s):

  • Error.TCPInvalidOperationError: Raised when the TCP option can't be set.

Parameter(s):

  • enabled (Boolean): True if the option should be enabled.
  • initialDelay (Number): The initial delay before the first keepalive probe is sent on an idle socket (>= 0).

connection.isNoDelay()

Get whether the TCP SO_NODELAY option was enabled.

Return value:

  • (Boolean) True if so.

connection.setNoDelay(enabled)

Set the TCP SO_NODELAY option.

Exception(s):

  • Error.TCPInvalidOperationError: Raised when the TCP option can't be set.

Parameter(s):

  • enabled (Boolean): True if the option should be enabled.

connection.getTimeout()

Get the TCP timeout.

Return value:

  • (Number) The timeout.

connection.setTimeout(timeout)

Set the TCP timeout.

Exception(s):

  • Error.TCPInvalidOperationError: Raised when the TCP option can't be set.

Parameter(s):

  • timeout (Number): The timeout (0 if not set).

connection.isOpened()

Get whether the TCP connection was opened.

Return value:

  • (Boolean) True if so.

connection.whenOpened([cancellator])

Wait for the connection to be opened.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise) The promise object (resolves when opened, rejects when cancelled).

connection.isErrorOccurred()

Get whether an error occurred.

Return value:

  • (Boolean) True if so.

connection.whenError([cancellator])

Wait for an error to be occurred.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise<Error.TCPError>) The promise object (resolves with an error when error occurred, rejects when cancelled).

connection.isClosed()

Get whether the connection was closed.

Return value:

  • (Boolean) True if so.

connection.whenClosed([cancellator])

Wait for the connection to be closed.

Exception(s):

  • Error.TCPOperationCancelledError: Raised when the cancellator was activated.

Parameter(s):

Return value:

  • (Promise) The promise object (resolves when closed, rejects when cancelled).

connection.close([forcibly])

Close the connection.

Exception(s):

  • Error.TCPEndOfStreamError: Raised when the connection was already closed.

Parameter(s):

  • forcibly (Boolean): (Optional) True if the connection should be closed forcibly.