I Get a Status 200 When Connecting to the Websocket, But It Is an Error

I get a status 200 when connecting to the websocket, but it is an error?

Please check http://procbits.com/connecting-to-a-sockjs-server-from-native-html5-websocket!

After you append /websocket (to your URL), it will give you the error

Failed to parse Origin header value [null]

;)
, which then will in turn lead you to that link.

You'll have to add .setAllowedOrigins("*") to your addHandler() method, and then it could finally work!

What is the WebSocket error on status 200?

On a WebSocket connection you want a 101 Switching Protocols status response.

Getting a 200 status response, probably means that the request didn't reach your WebSocket Handler.

I would also look into the dev-tools, and check if the response has any WebSocket handshake headers.

If it has, I would assume it's a problem with the module. Otherwise it's probably your configuration.

WebSockets WS error during WebSocket handshake: Unexpected response code: 200

The ws Server constructor does not accept an app option, so your wss isn't actually listening to anything. If this exact code did work locally, it's hard to see how.

Since you're attempting to connect to a WebSocket that shares the same path as your page, the express app ends up handling the WebSocket client request and responds with your page HTML.

Your HTTP exchange ends up looking something like this — first the browser loads the page:

GET /page HTTP/1.1
Accept: text/html


HTTP/1.1 200 OK
Content-Type: text/html

<html> …

Then the page makes a new WebSocket(…), resulting in a WebSocket upgrade request:

GET /page HTTP/1.1
Connection: Upgrade
Upgrade: websocket


HTTP/1.1 200 OK
Content-Type: text/html

<html> …

You should see why this would fail: that's not a WebSocket response. Express thinks the request is a regular HTTP GET request and responds with your page's HTML. The browser's WebSocket implementation sees a response that does not conform to the WebSocket spec and rightly throws an error. It reports "status 200" because the server did respond with a HTTP 200 status code — even though it was an accident.

The correct way to attach a ws Server to a HTTP server is to either:

  1. Pass in the http.Server (not the express app) to ws.Server's server option

    var app = express(),
    server = http.createServer(app),
    wss = new ws.Server({ server });

    server.listen(process.env.PORT);
  2. Or manually attach an upgrade listener to your http.Server and call wss.handleUpgrade.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 200

You are using a WebSocket client to connect to a Socket.IO server. Use a Socket.IO client and you will be fine. WebSocket is not the same as Socket.IO, the latter is implemented on top of WebSocket and uses a different protocol.



Related Topics



Leave a reply



Submit