lowjumpingfrog
lowjumpingfrog

Reputation: 33

Making TCP connections from Meteor Server

I need some advice regarding meteor. I would like to move an existing express/node.js app over to the meteor framework to take advantage of server storage - MongoDB and the MVC nature of the framework. My app needs a major refactoring. My current app server makes a TCP connection to a remote host that spits out string data every second. This app server manipulates the string data from the remote host and then sends it to the app clients. Since meteor uses node.js I would imagine this would be as simple as moving the part of my current app server code that does the TCP connection into the meteor server code. Is this solid logic or is there a snake in the grass to this approach?

Of course there is always try it and see what happens. I put something like this in the Meteor.startup()

var net = Npm.require('net'),
    dataStream = net.createConnection(5000,"localhost");
dataStream.setEncoding('utf8');
dataStream.on('data', function(data) {
    var line = data.trim();
    Messages.insert({name:"line",message: line, time:Date.now()});
});

I am getting a complaint about Meteor code running outside a fiber. Is updating a collection that is visible to the client and server the right way to go here? I am assuming the updates will stay on the server and get push to the client where I'll have a view to display the changes.

Upvotes: 1

Views: 1906

Answers (2)

m.jansink
m.jansink

Reputation: 224

I ran into the exact same issue (actually, I was making a TCP server instead of a client), but solved it by adding Meteor.bindEnvironment around each callback function. Like:

// ..set- and fire up a tcp server..
var server = net.createServer( Meteor.bindEnvironment( function ( socket ) {
  // ..with a listener that processes the commands..
  socket.addListener( "data", Meteor.bindEnvironment( function ( data ) {

    // ..working with collections now just works!

  } ) );
} ) ).listen( port );

For a good explanation on this method, see https://www.eventedmind.com/feed/meteor-what-is-meteor-bindenvironment.

Upvotes: 5

Christian Fritz
Christian Fritz

Reputation: 21364

Yes, this is roughly how it can work. I've just finished finished moving an expressjs app to meteor and that's pretty much how I did it.

Some things I had to do (and that I suspect you'll need to:)

  • use Npm.require('...') in place of require('...')
  • use iron-router to handle different server side routes
  • for each use of app.get(.. etc. create a server side route in iron router
  • redefine res/req in the express routes to point to this.response/this.request respectively and change any special functions defined by express to work again based on the underlying connect middleware (e.g., res.cookie(), req.header(), ..)

Update: For more details, see Is there an easy way to convert an express app to meteor?.

Upvotes: 2

Related Questions