Reputation: 111
So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:
const WebSocket = require('ws');
var express = require('express');
var app = express();
wss = new WebSocket.Server({server : app});
app.get('/', function(req, res){
res.send('hello world!');
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('some text');
});
app.listen(8080, function(){
console.log('app started');
});
If I then load the servers website in chrome-browser I am greeted with "hello world!". So far so good. But if I open up the webconsole and try to connect with
var exampleSocket = new WebSocket("ws://192.10.10.30:8080");
I get the following errormessage:
WebSocket connection to 'ws://192.10.10.30:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200
My first thought was, do I have to explicitly declare an http-server ?
But I read this post Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.
Upvotes: 3
Views: 3927
Reputation: 11
I was having this issue on a Windows machine and discovered the reason was IIS did not have the WebSocket Protocol turned on. Ensure IIS on the machine supports WebSocket: Control Panel -> Programs and Features -> Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then ensure WebSocket Protocol is checked.
Upvotes: 1
Reputation: 203514
You're passing an Express app instance as server
, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen
:
var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});
wss = new WebSocket.Server({server : server});
Upvotes: 7