0

我在 Stackoverflow 上找到了一个简单的 MQTT 代理示例:

Typescript / MQTT / Node - 如何从回调函数访问类成员?

但是当我尝试重新创建它时出现错误:

This expression is not callable:

this.aedes=aedes();

它说它找不到这个函数 aedes()。我的代码有什么问题?

代码:

经纪人.ts

import * as aedes from 'aedes';
import * as net from 'net';

export class Broker {

    aedes: aedes.Aedes;
    broker: net.Server;
    port: number;

    constructor(port: number){
        this.aedes=aedes();
        this.broker = net.createServer(this.aedes.handle);
        this.port = port;
        this.broker.listen(this.port, () => {
            console.log('MQTT is listening.');
        });
    }
    
    /** 
     * This is a callback register function
     *
     * Callback function must have a signature of type : function(topic: string, payload: string)
     **/
    onMsgReceived(callback: {(topic: string, payload: string): void}){
        this.aedes.on('publish', (packet, client) => {
            if (packet.cmd != 'publish') return;
            callback(packet.topic, packet.payload.toString());
        });
    }

}

测试.ts

export class Test {
    someVar: string;

    constructor() {
        this.onMsgReceivedCallback = this.onMsgReceivedCallback.bind(this);
    }

    onMsgReceivedCallback(topic: string, payload: string) {
        console.log(`someVar: ${this.someVar}`);
    }
}

main.ts

import { Broker } from './broker'
import { Test } from './test'

console.log("main.ts");

const broker = new Broker(1883);
const broker2 = new Broker(4340);
const test   = new Test();


broker.onMsgReceived(test.onMsgReceivedCallback);

谢谢您的帮助!

4

1 回答 1

0

我遇到了类似的问题,并且能够使用以下更改来解决它:

constructor(port: number){
        // this.aedes=aedes();
        this.aedes = aedes.Server();

        this.broker = net.createServer(this.aedes.handle);
        this.port = port;
        this.broker.listen(this.port, () => {
        console.log('MQTT is listening.');
    });
} 
于 2022-02-20T13:19:41.473 回答