【问题标题】:Firefox can’t establish a connection to the server at wss://localhost:8000/Firefox 无法在 wss://localhost:8000/ 建立与服务器的连接
【发布时间】:2021-12-06 00:00:02
【问题描述】:

我使用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/ 处建立与服务器的连接。

【问题讨论】:

    标签: javascript node.js websocket


    【解决方案1】:

    您的实施需要进行一些更改。在后端服务器中,您忘记调用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 服务器的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 2020-04-06
      相关资源
      最近更新 更多