Sha256: 6b10d9a0910f54b5f35db733e4688a8465b159b48862855b56963b15363da958

Contents?: true

Size: 1.97 KB

Versions: 2

Compression:

Stored size: 1.97 KB

Contents

const { IConnectionData, ConnectionType } = require('../../..')
const dns = require('dns')

/**
 * @extends IConnectionData
 */
class TcpConnectionData extends IConnectionData {
    constructor(hostname, port) {
        super()
        this._port = port
        this._hostname = hostname
        this._connectionType = ConnectionType.TCP
        if (hostname === 'localhost') {
            this.ipAddress = '127.0.0.1'
        } else {
            this.ipAddress = this.resolveIpAddress(hostname)
        }
    }

    get connectionType() {
        return this._connectionType
    }

    get hostname() {
        return this._hostname
    }

    /**
     * @param {TcpConnectionData} other
     * @returns {boolean}
     */
    equals(other) {
        if (other instanceof TcpConnectionData) {
            return this.ipAddress === other.ipAddress && this._port === other._port
        }
        return false
    }

    /**
     * @param {string} hostname
     * @returns {string|null}
     */
    resolveIpAddress(hostname) {
        // Check if the input is an IP address
        const ipPattern = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
        if (ipPattern.test(hostname)) {
            // If it's an IP address, return it directly
            return hostname
        } else {
            // If it's not an IP address, try to resolve it as a hostname
            return dns.resolve4(hostname, (err, addresses) => {
                if (err) {
                    console.error(err)
                    return null
                }
                return addresses[0]
            })
        }
    }

    serializeConnectionData() {
        let result = [this.connectionType]
        result = result.concat(this.#getAddressBytes())
        result = result.concat(this.#getPortBytes())
        return result
    }

    #getAddressBytes() {
        return this.ipAddress.split('.').map(Number)
    }

    #getPortBytes() {
        return [this._port & 0xff, this._port >> 8]
    }
}

module.exports = TcpConnectionData

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
javonet-ruby-sdk-2.5.10 lib/javonet-ruby-sdk/Binaries/Nodejs/lib/utils/connectionData/TcpConnectionData.js
javonet-ruby-sdk-2.5.9 lib/javonet-ruby-sdk/Binaries/Nodejs/lib/utils/connectionData/TcpConnectionData.js