[英]Firefox can’t establish a connection to the server at ws://localhost:8080/
[英]Firefox can’t establish a connection to the server at wss://localhost:8000/
我正在使用nodejs運行服務器,沒有日志文件
這是我的 server.js
const https = require('https');
const fs = require('fs');
const ws = require('ws');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
const wss = new ws.Server({noServer: true});
function accept(req, res) {
// all incoming requests must be websockets
if (!req.headers.upgrade || req.headers.upgrade.toLowerCase() != 'websocket') {
res.end();
return;
}
// can be Connection: keep-alive, Upgrade
if (!req.headers.connection.match(/\bupgrade\b/i)) {
res.end();
return;
}
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onConnect);
}
function onConnect(ws) {
ws.on('message', function (message) {
let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu) || "Guest";
ws.send(`${name}!`);
//setTimeout(() => ws.close(1000, "Bye!"), 5000);
});
}
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
這是我的反應代碼
componentDidMount() {
var connection = new WebSocket('wss://localhost:8000/');
connection.onopen = function(e) {
connection.send("add people");
};
connection.onmessage = function(event) {
// alert(`[message] Data received from server: ${event.data}`);
console.log("output ", event.data);
};
}
當我嘗試使用我的 jsx 文件連接 web-socket 時,它給了我一個錯誤,即Firefox 無法在 wss://localhost:8000/ 上建立到服務器的連接。
您的實現需要一些更改。 在后端服務器中,您忘記調用onConnect
函數。 所以你的ws.on
方法永遠不會調用。
此外,您導入了ws
並創建了一個 WebSocket 服務器wss
,但是您錯誤地在ws
上添加了一些事件偵聽器,您應該在 Websocket 實例( wss
)上添加偵聽器:
// rest of the codes ...
const was = new ws.Server({noServer: true})
wss.on('connection`) {
// do something here ...
}
// rest of the codes ...
https.createServer(options, () => {
// do something here ...
})
在ws
npm page上有一些關於如何創建 WebSocket 服務器和 HTTP 服務器的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.