2014-02-07 66 views
7

如何从Meteor打开Websockets连接?从Meteor.js打开Websocket连接

我们可以这样做:

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

错误:ReferenceError: WebSocket is not defined


使用socket.io NPM包

var io = Meteor.require('socket.io') 
var socket = io.connect('http://localhost'); 

错误:TypeError: Object #<Object> has no method 'connect'


使用WS NPM包

var WebSocket = Meteor.require('ws'); 
var ws = new WebSocket('ws://localhost'); 

错误:Error: Cannot find module '../build/default/bufferutil'

回答

0

有一个包叫做Meteor Streams,可以让你做同样的事情,使用现有的流星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); 
    }); 
} 

我不确定你想连接到另一台服务器或本地的,如果它的另一个你可以使用你提供的例子。我建议在客户端不允许使用websocket的情况下使用其他类似SockJS或socket.io(因此需要websocket仿真)。

+1

我会喜欢连接到非流星Websocket服务。使用我的例子,我得到错误'ReferenceError:WebSocket未定义'。我尝试了'socket.io' npm包但是使用'Meteor.require('socket.io').connect('http:// localhost'),我得到错误'Object# has no method'connect'' – Nyxynyx

+0

你在客户端的服务器上做这个吗? – Akshat

+0

尝试使用faye-websockets npm模块,如果从服务器@ https://npmjs.org/package/faye-websocket – Akshat

4

我创建了一个新的流星包joncursi:socket-io-client来解决这个问题。有关更多详细信息和示例用法,请参阅https://atmospherejs.com/joncursi/socket-io-client。由于我已将NPM二进制文件捆绑到一个包中,因此您不必担心安装NPM包,声明NPM.require()依赖关系等。最重要的是,您可以顺利部署到.meteor.com

+1

有没有一种方法可以将这种方法用于没有socket.io连接的普通websockets连接? – digitalWestie

0

根据这个问题的答案,是指openshift博客文章, 你的回答是: (问题:How to set Meteor WebSocket port for clients?

I struggled with this for a while now and I tried different things. The solution that worked for me in OpenShift was this:

Set the DDP_DEFAULT_CONNECTION_URL variable

//for http 
process.env.DDP_DEFAULT_CONNECTION_URL = 'http://' + process.env.OPENSHIFT_APP_DNS + ':8000' 
//for ssl 
process.env.DDP_DEFAULT_CONNECTION_URL = 'https://' + process.env.OPENSHIFT_APP_DNS + ':8443' 

According to this blog post: https://www.openshift.com/blogs/paas-websockets