从Meteor.js打开Websocket连接

Nyx*_*nyx 8 javascript websocket node.js npm meteor

我们如何从Meteor打开Websockets连接?

我们可以这样做:

ws = new WebSocket('ws://localhost/path');
ws.on('open', function() {
    ws.send('something');
});
ws.on('message', function(message) {
    console.log('received: %s', message);
});
Run Code Online (Sandbox Code Playgroud)

错误:ReferenceError:未定义WebSocket


使用socket.io npm包

var io = Meteor.require('socket.io')
var socket = io.connect('http://localhost');
Run Code Online (Sandbox Code Playgroud)

错误:TypeError:对象#没有方法'connect'


使用ws npm包

var WebSocket = Meteor.require('ws');
var ws = new WebSocket('ws://localhost');
Run Code Online (Sandbox Code Playgroud)

错误:错误:找不到模块'../build/default/bufferutil'

Aks*_*hat 0

有一个名为Meteor Streams 的包,可以让你做类似的事情,使用现有的 Meteor Websocket 连接到本地服务器:

chatStream = new Meteor.Stream('chat');

if(Meteor.isClient) {
  sendChat = function(message) {
    chatStream.emit('message', message);
    console.log('me: ' + message);
  };

  chatStream.on('message', function(message) {
    console.log('user: ' + message);
  });
}
Run Code Online (Sandbox Code Playgroud)

我不确定您想要连接到另一台服务器还是本地服务器,如果是另一台服务器,您可以使用您提供的示例。如果客户端不允许使用 websocket(因此需要 websocket 模拟),我建议使用其他东西,例如 SockJS 或 socket.io。