简体   繁体   中英

Open a Websocket connection from Meteor.js

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'

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.

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).

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

您可以尝试这里是解决方案: https : //github.com/Akryum/meteor-socket-io

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM