Reputation: 63619
How can we open a Websockets connection from Meteor?
Can we do something like:
ws = new WebSocket('ws://localhost/path');
ws.on('open', function() {
ws.send('something');
});
ws.on('message', function(message) {
console.log('received: %s', message);
});
Error: ReferenceError: WebSocket is not defined
Using socket.io npm package
var io = Meteor.require('socket.io')
var socket = io.connect('http://localhost');
Error: TypeError: Object # has no method 'connect'
Using ws npm package
var WebSocket = Meteor.require('ws');
var ws = new WebSocket('ws://localhost');
Error: Error: Cannot find module '../build/default/bufferutil'
Upvotes: 8
Views: 13527
Reputation: 2756
You can try here is the solution: https://github.com/Akryum/meteor-socket-io
Upvotes: 0
Reputation: 533
According to this question's answer which refers to an openshift blog post, you answer is: (question : 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
Upvotes: 0
Reputation: 3371
I created a new Meteor package joncursi:socket-io-client
to solve this problem. Please see https://atmospherejs.com/joncursi/socket-io-client for more detail and example usage. Since I've bundled the NPM binaries into a package for you, you don't have to worry about installing NPM packages, declaring NPM.require()
dependencies, etc. And best of all, you can deploy to .meteor.com
without a hitch.
Upvotes: 4
Reputation: 75945
There is a package called Meteor Streams, that can let you do something similar, using the existing meteor websocket to connect to the local server:
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);
});
}
I'm not sure you wanted to connect to another server or the local one, if its another one you can use the example you have provided. I would recommend using something else like SockJS or socket.io in the case where websockets aren't permitted on the client side (and hence websocket emulation is required).
Upvotes: 0