Search code examples
javascriptwebsocketconnection-refused

net::ERR_CONNECTION_REFUSED using websockets


I'm trying to create a websocket without any framework, in vanilla JavaScript.

I'm trying to send a basic text websocket, but it keeps throwing me the error net::ERR_CONNECTION_REFUSED

Here's the code on repl.it

I have a Content Security Policy set:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">

my websocket is set to ws://localhost/ at the 9000 port.

Anyway here's my script.js file:

let a = new WebSocket("ws://localhost:9000");
a.onopen = () => {
  setTimeout(() => {
    a.send("working?");
  }, 1000);
};
a.onmessage = (event) => {
  console.log(event.data);
}
and my srv.js (in nodejs) file:

let server = require('ws').Server;
let srv = new server({port: 9000});
srv.on('connection', ws => {
  ws.on('message', msg => {
    console.log(`Received message => ${msg}`)
  })
  ws.send('hey')
})


Solution

  • I saw that this old question of mine hasn't been answered, after that i dig into websockets and figured out that the problem I think was that I didn't set 'Access-Control-Allow-Origin': "*" in the server With ws it would be:

    let server = require('ws').Server;
    let srv = new server({port: 9000, 'Access-Control-Allow-Origin': "*"});
    srv.on('connection', ws => {
      ws.on('message', msg => {
        console.log(`Received message => ${msg}`)
      })
      ws.send('hey')
    });
    

    Although my question is incorrect as ws is an external module that helps with websockets, anybody who thinks that making a websocket server without this module is easy is wrong, it is possible but the amount of code for just a simple server like in my question takes almost 50 lines of code which is not worth it, as ws has many features that makes it easy and more reliable than without using external modules.

    For anybody who wants to actually make it for learning purposes here's the websocket protocol explained, but since they don't provide code I made a repl on repl.it