Meteorjs equivalent of ws.send

28 Views Asked by At

Im trying to send a simple message that event has happened on the backend, specifically i have a observable that listens if anything changed/update in mongodb then updates the related record in elasticsearch.

Is there a Meteor equivalent of ws.send() on backend and use ws.on() on frontend?

How do i do that with Meteor?

I know of Meteor.publish/subscribe but its not quite the same and it does not fit my need

1

There are 1 best solutions below

1
Jankapunkt On BEST ANSWER

Meteor only abstracts the Websocket away for you but it's still there. However, by doing to it also forces you to follow a certain pattern.

First, your need to track the connections on the Meteor-level, using Meteor.onConnection.

Then you need to get the correct socket instance for this connection which you want to send the message to:

server

import { Meteor } from 'meteor/meteor';

Meteor.startup(() => {
  Meteor.onConnection(connection => {
    const socket = Meteor.server.stream_server.open_sockets.find(s => s._meteorSession.id === connection.id)
    socket.send(JSON.stringify({
      msg: 'foo',
      custom: 'data'
    }))
  })
});

You can of course always send the message to all connected clients using Meteor.server.stream_server.open_sockets (array of instance-refs).

client

Meteor.startup(() => {
  Meteor.connection._stream.on('message', (dataStr) => {
    const data = JSON.parse(dataStr)

    // this is your custom message
    if (data.msg === 'foo') {
      console.debug(data)
    }
  })
})

What#s left, and what is then up to you is to find the right client by connection that was requesting this message and at that point you might get back to pub/sub or customize pub/sub to run without a collection.