javascript - ws WebSocket 客户端是否损坏? echo.websocket.org 演示在本地运行时失败并显示 404

标签 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 服务器,并使用 SwiftWebSocket 创建了 WebSocket 客户端。在 iOS 上,并且能够成功打开连接。然后我将上面的代码指向这个新 URL,但连接仍然失败。

ws客户端坏了吗?

最佳答案

以下是在浏览器中按原样工作的稍微简化:

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

只需终止 require,并将 on 更改为 addEventListener...

您应该能够在第一行使用任何有效的 URL。

关于javascript - ws WebSocket 客户端是否损坏? echo.websocket.org 演示在本地运行时失败并显示 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38533791/

相关文章:

node.js - Django channel 与 Node socket.io

ajax - 如何实现 cometd ?

javascript - 将多维数组的内容转储到新的 JSON 变量中

mysql - Nodejs Passport 设置困惑

javascript - 在 javascript 中使用 Html.DropDownList

javascript - 如何在javascript中引用目录

node.js - 如何使用 NodeJS 和 Google Drive API v3 将文件移动到回收站

javascript - 用于大量数据的 WebSockets 与 XHR

javascript - Javascript 引擎中的尾调用优化实现

javascript - 无法理解下面代码片段中的break master的用法