Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

websockets, express.js and can’t establish a connection to the server

This is simple chat on WS and express.js. I get the error that the browser can't connect to server via websockets.

client connection:

file: rtc.html 
ws = new WebSocket('wss://' + window.location.hostname + '/wr' );
ws.onerror = (error) => { console.log(error); };
ws.onmessage = (message) => {
   . . . 

Server code:

const express =   require('express');
const http =      require('http');
const WebSocket = require('ws');

const app = express();

app.get('/rtc', (req, res)=>{
  res.sendFile('/home/user/dev/rtc.html');
});

const server = http.createServer(app);
const wss = new WebSocket.Server({ server:server, path: "/wr" });

. . . 

app.listen(3000);

UPD: The problem was due to the fact that I was doing chat on webrtc and tested in Mozilla and Mozilla would not connect without https connection however getUserMedia ran fine. It was necessary to write so:

var https = require('https');
var serv = https.createServer(serverConfig, app);
like image 983
alex10 Avatar asked Nov 30 '25 14:11

alex10


1 Answers

Change from:

app.listen(3000);

to:

server.listen(3000);

When you use app.listen(), it creates a new http server and thus the one you connected socket.io to is never started. To fully understand app.listen(), the code for it looks like this:

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

So, you can see it was creating a different http server than the one you attached your webSocket server to and thus that other one was never started.


Alternatively, you could also do this:

const server = app.listen(3000);
const wss = new WebSocket.Server({ server:server, path: "/wr" });

And, not create your own http server at all. app.listen() returns the new server object that it created.

like image 151
jfriend00 Avatar answered Dec 02 '25 04:12

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!