简体   繁体   中英

Node.js with express and websocket giving error during WebSocket handshake: Unexpected response code: 200

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.

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

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