简体   繁体   中英

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);

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.

just make sure you use server.listen().Rest the code speaks itself

  var express = require('express'), app = express(), http = require('http'), server = http.createServer(app), WebSocketServer = require('ws').Server, wss = new WebSocketServer({ server }); app.use(express.static(__dirname)); server.listen(process.env.PORT || 3000, function () { // console.log("Node server is running on http://localhost:3000/"); }); wss.on('connection', function (ws) { //console.log("New connection."); ws.on('message', function (message) { //console.log("Message received:", message); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM