I’m running the echo.websocket.org demo for the ws WebSocket library on my local machine.
var WebSocket = require('ws');
var ws = new WebSocket('ws://echo.websocket.org/', {
protocolVersion: 8,
origin: 'http://websocket.org'
});
ws.on('open', function open() {
console.log('connected');
ws.send(Date.now().toString(), {mask: true});
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function message(data, flags) {
console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags);
setTimeout(function timeout() {
ws.send(Date.now().toString(), {mask: true});
}, 500);
});
I compiled this code with Browserify (details in the repo) and tested it in Chrome and Safari.
It fails with a 404 on Chrome 51.0.2704
Fetch API cannot load http://echo.websocket.org/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
It fails with a 400 on Safari 9.1.1
Failed to load resource: the server responded with a status of 400 (WebSocket Upgrade Failure)
In troubleshooting this, I set up a local WebSocket server with Node.js/Express, created a WebSocket client using SwiftWebSocket on iOS, and was able to open a connection successfully. I then pointed the code above to this new URL, and the connection still fails.
Is the ws client broken?