2014-02-07 68 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