我使用 aedes 创建服务器,如下所示:
const aedes = require('aedes')()
const httpServer = require('http').createServer()
const ws = require('websocket-stream')
const port = 8888
ws.createServer({ server: httpServer }, aedes.handle)
httpServer.listen(port, function () {
console.log('websocket server listening on port ', port)
})
此代码在端口 8888 上运行正常。在 Reactjs 中使用 mqtt-react-hooks 之后,我创建了文件:
import React from 'react';
import { Connector } from 'mqtt-react-hooks';
import { useMqttState } from 'mqtt-react-hooks';
export default function App() {
const { connectionStatus } = useMqttState();
return (
<Connector brokerUrl="mqtt://domain.com:8888">
<h1>{`Status: ${connectionStatus}`}</h1>
</Connector>
);
}
发生错误:显示状态:未定义。网络损坏和过载。我尝试在网络浏览器上通过 websocket 使用 MQTT,所以需要另外设置吗?
更新: 我使用 tls,所以它必须与 key、cert、ca 一起使用。使用上面的代码,浏览器发送状态强制使用 wss。我更改服务器文件如下:
const fs = require('fs');
const aedes = require('aedes')();
var wsSslPort = 8888;
var ws = require('websocket-stream');
// WsSsl server
var wsSslServer = require('https').createServer({
key: fs.readFileSync("cert/key.pem"),
cert: fs.readFileSync("cert/crt.pem"),
requestCert: false, // client send their certificate
rejectUnauthorized: false,
ca: [ fs.readFileSync("cert/ca.ca") ]
}, aedes.handle);
wsSslServer.listen(wsSslPort, "domain.com", function () {
console.log('MQTT websocket tls server listening on port', wsSslPort)
});
此代码运行正常。
我还更改了客户端文件:
import React from 'react';
var optionsMqtt={
clientId: uuidv4(),
rejectUnauthorized : false,
ca: cert_mqtt.ca_mqtt,
key: cert_mqtt.key_mqtt,
cert: cert_mqtt.crt_mqtt
}
const websocketUrl = "wss://domain.com:8888";
export default function App() {
const client = mqtt.connect(websocketUrl,optionsMqtt);
client.stream.on("error", (err) => {
console.log(`Connection to ${websocketUrl} failed`);
client.end();
});
client.on('connect', function () {
console.log('Connected');
});
return (
<>
<h1>TEST</h1>
<>
);
}
仍然出错:
<块引用>ws.js:108 WebSocket 连接到“wss://domain.com:8888/”失败: 连接建立错误:net::ERR_CONNECTION_REFUSED
我也关闭了防火墙,打开了 8888 端口。
答案 0 :(得分:2)
您已通过在 URL 中使用 mqtt://
架构明确告知客户端使用本机 MQTT。
将其更改为 ws://