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://' +
Solution 1:
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.
Solution 2:
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);
});
Post a Comment for "Websockets, Express.js And Can’t Establish A Connection To The Server"