Sending arbitrary messages to client from sockjs socket created by DDP connection?


#1

I would like to send arbitrary messages to an specific DDP client.

For instance calling “write” from the server:

Meteor.server.sessions[ session_id ].socket.write( { data_for_user: "something" } )

But i’m not sure how i’m supposed to “catch” this messages on the client. I know the following code doesn’t work, but i would like to achieve something among this lines:

DDP.client.onmessage( function( data ) { 
  // i'm guessing i would have to filter my messages, since all DDP messages would come here?
  if( data.data_for_user ) {
    // Do i need to tell DDP to don't parse my custom message?
    console.log( "got something for you", data )
  }
} );

#2

It’s not perfect. But something like this should do the trick.

If your users are logged in, you can use this.userId in Meteor.publish to tailor what they see.

if (Meteor.isServer){
  Meteor.publish('interesting.messages', function(){
    // must call this.ready()
    this.ready();
    var pseudoCollection = 'amusing.data',
        stack = [], 
        STACK_LENGTH=10;
    
    // Create a message every second
    Meteor.setInterval(function(){
      var messageId = Random.id();
      stack.push(messageId);
      this.added(pseudoCollection, messageId, {time: Date.now()});
      
      // only have STACK_LENGTH messages published at any one time
      //  this could cause a user to miss messages if they're published too quickly.
      //  Or, it could waste memory if we set STACK_LENGTH too high
      while(stack.length > STACK_LENGTH){
        // get rid of the oldest message first
        var removeId = stack.shift();
        this.removed(pseudoCollection, removeId);
      }
    }.bind(this), 1000);
  });
}
if (Meteor.isClient){
  var amusingData = new Mongo.Collection('amusing.data');
  Meteor.subscribe('interesting.messages');
  amusingData.find().observe({
    added: function(msg){
      console.log('message from server', msg);
    }
  })
}

#3

I came across this topic by wanted to push data to the client via DDP

If I understand well, the this.added function push information in the pseudoCollection ( but this does create a Mongo collection right ? ( you just only limiting the number of record to 10 ?

And then you push the message via DDP to all subscribed client ?

If I wanted to create a multiplier game w/o using a Mongo collection is their a specific way to go ?

Socket ?
DDP ?

ps: I know this post is old, but I want to know if their is a better way or this is still the way to go to build multiplayer game using meteor ?


#4

No. The pub/sub API manages a client-only minimongo (in-memory) collection. No actual (on-disk) MongoDB collection is created.