好吧,我已经经历了很多试错,但我已经成功了。
在我说出答案之前,我会告诉你什么不能做。
Socket.io 客户端
我从 socket.io-client 开始。感谢 Twitter 上的某个人,我发现 socketio 客户端永远无法工作,因为客户端有一个特定的握手来建立连接。 (我找不到我的来源)
AutobahnJS
所以下一个选项:AutobahnJS,我在 Ratchet 的网站上看到它通过了 Autobahn 测试套件 http://socketo.me/docs/wamp。 Peanuts 我想,但我没有让它工作,因为当前版本的 AutobahnJS 不支持“旧”版本的 WAMP (https://groups.google.com/forum/#!topic/ratchet-php/Szd2VV4EtXs),但 AutobahnJS 0.8.* 应该。不幸的是,您无法使用 NPM 安装该版本。
vagrant@dev:/var/www/quadstation.dev/quadstation-frontend$ sudo npm install autobahn@0.8.*
npm WARN package.json groundstation-quadcopter@0.0.1 No repository field.
npm ERR! Linux 3.13.0-32-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "autobahn@0.8.*"
npm ERR! node v0.12.0
npm ERR! npm v2.5.1
npm ERR! code ETARGET
npm ERR! notarget No compatible version found: autobahn@'>=0.8.0 <0.9.0'
npm ERR! notarget Valid install targets:
npm ERR! notarget ["0.0.0","0.9.0","0.9.0-2","0.9.0-3","0.9.0-4","0.9.0-5","0.9.1","0.9.1-3","0.9.1-4","0.9.2","0.9.3","0.9.4","0.9.4-2","0.9.5","0.9.6"]
npm ERR! notarget
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! Please include the following file with any support request:
npm ERR! /var/www/quadstation.dev/quadstation-frontend/npm-debug.log
vagrant@dev:/var/www/quadstation.dev/quadstation-frontend$ npm install https://github.com/tavendo/AutobahnJS/archive/v0.8.2.tar.gz
npm WARN package.json groundstation-quadcopter@0.0.1 No repository field.
npm ERR! Linux 3.13.0-32-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "https://github.com/tavendo/AutobahnJS/archive/v0.8.2.tar.gz"
npm ERR! node v0.12.0
npm ERR! npm v2.5.1
npm ERR! path /tmp/npm-30480-482d323b/unpack-e44042007b9f/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! enoent ENOENT, open '/tmp/npm-30480-482d323b/unpack-e44042007b9f/package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent
npm ERR! Please include the following file with any support request:
npm ERR! /var/www/quadstation.dev/quadstation-frontend/npm-debug.log
Websocket 节点
在那之后我变得绝望并尝试了Websockets-Node,但我没有更进一步然后连接被拒绝,但我没有得到任何关于为什么或如何解决它的明确原因。
那么正确的解决方案是什么? WS和大量阅读
我之前尝试过 ws,但经过一些额外的阅读后,我给了它第二次机会,直到我改变了一些东西,我才让它工作。我的初始代码如下所示:
var WebSocket = require('ws');
var ws = new WebSocket('ws://localhost:3344/', {
protocolVersion: 8,
origin: 'http://localhost'
});
在阅读了一些协议后,我发现 protocolVersion 13 与 rfc6455 + What are the protocol differences between WebSockets versions? 相关
我还发现(感谢这个帖子:https://code.google.com/p/chromium/issues/detail?id=36652)使用 localhost 也让我很头疼。我改成127.0.0.1,终于搞定了。
var WebSocket = require('ws');
var ws = new WebSocket('ws://127.0.0.1:3344/', {
protocolVersion: 13,
origin: 'http://127.0.0.1'
});
如果有人对此有其他疑问,请告诉我。