如何围绕现有的 tcp 套接字包装 mqtt 客户端?

How to wrap a mqtt client around an existing tcp socket?

我处于这样一种情况,我需要在现有的 tcp 套接字周围包装一个 mqtt.Client 以访问有关刚刚打开的连接的一些信息(例如 localAddress 和 localPort)。是否可以在打字稿中做这样的事情?

import * as mqtt from 'mqtt';
import * as net from 'net';
class Client
{
    private _client: mqtt.Client;
    private _socket: net.Socket;

    constructor()
    {
        this._socket = net.createConnection({host: 'my_host', port: 1234}, () => 
        {
            this._client = new mqtt.Client(this._socket, {
                // options here.
            });

            // Access the socket info
            // this._socket.localAddress
            // this._socket.localPort
        });
    }
}

或者是否有另一种方法可以重用 mqtt.connect 函数打开的同一个 tcp 套接字? 感谢您的帮助!

我正在使用这个 npm module 来实现客户端。

我已经设法通过 mqtt API 对其进行调整。 如果您遇到此问题,只需从存储在客户端中的嵌入式 stream 对象中获取您需要的信息。 像这样:

import * as mqtt from 'mqtt';
class Client
{
    private _client: mqtt.Client;

    constructor()
    {
        this._client = mqtt.connect(`mqtt://${URL_GOES_HERE}`, {
            // options here.
        });

        this._client.on('connect', () =>
        {
            let address = this._client.stream.localAddress;
            let port = this._client.stream.localPort;
        });
    }
}