我在 Stackoverflow 上找到了这个简单的 MQTT Broker 示例:
Typescript / MQTT / Node - How to acces class member from a callback function?
但是当我尝试重新创建它时出现错误:
Path(filePath).read_text()
它说它找不到这个函数 aedes()。我的代码有什么问题?
代码:
broker.ts
This expression is not callable:
this.aedes=aedes();
test.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());
});
}
}
main.ts
export class Test {
someVar: string;
constructor() {
this.onMsgReceivedCallback = this.onMsgReceivedCallback.bind(this);
}
onMsgReceivedCallback(topic: string, payload: string) {
console.log(`someVar: ${this.someVar}`);
}
}
感谢您的帮助!