javascriptnode.jswebsocket

Firefox can’t establish a connection to the server at wss://localhost:8000/


I am using nodejs to run the server, there is no log file

This is my 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);

This is my code in 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);
      
    };
}

While I am trying to connect with web-socket with my jsx file its give me an error which is Firefox can’t establish a connection to the server at wss://localhost:8000/.


Solution

  • Your implementaion needs some changes. In the backend server, you forgot to call the onConnect function. So your ws.on method will never call.

    Also, you imported the ws and create a WebSocket server wss, but you add some event listener on ws wrongly, you should add listener on your Websocket instance (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 ...
    })
    

    There are some examples of how to create the WebSocket server along with the HTTP server on ws npm page.