websocket Firefox无法在wss://localhost:8000/建立到服务器的连接

dphi5xsq  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(588)

我用的是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);

字符串
这是我在react中的代码

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/服务器的连接。

bnlyeluc

bnlyeluc1#

你的实现需要一些改变。在后端服务器中,您忘记调用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 ...
})

字符串
这里有一些关于如何在wsnpm page上创建WebSocket服务器沿着HTTP服务器的示例。

相关问题