ws WebSocket客户端坏了吗?当本地运行时,echo.websocket.org演示失败并显示404

时间:2016-07-22 19:12:24

标签: javascript node.js websocket

我在本地计算机上运行ws WebSocket library的echo.websocket.org演示。

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

我使用Browserify编译了此代码(repo中的详细信息)并在Chrome和Safari中对其进行了测试。

Chrome 51.0.2704上的404失败

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.

在Safari 9.1.1上失败了400

Failed to load resource: the server responded with a status of 400 (WebSocket Upgrade Failure)

在对此进行故障排除时,我使用Node.js / Express设置了本地WebSocket服务器,在iOS上使用SwiftWebSocket创建了一个WebSocket客户端,并且能够成功打开连接。然后我将上面的代码指向这个新URL,连接仍然失败。

ws客户端坏了吗?

2 个答案:

答案 0 :(得分:0)

我误解了WebSocket是如何工作的。

WebSocket是this post,在standard中实现。您不需要单独的库。以下Javascript是建立WebSocket连接所需的全部内容。

ModeValue

答案 1 :(得分:0)

这是一个稍微简化,适用于浏览器:

var ws = new WebSocket('ws://echo.websocket.org/');

ws.addEventListener('open', function open() {
  console.log('connected');
  ws.send(Date.now().toString(), {mask: true});
});

ws.addEventListener('close', function close() {
  console.log('disconnected');
});

ws.addEventListener('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);
});

只需删除要求,然后将on更改为addEventListener ...

您应该可以在第一行使用任何有效的网址。