简体   繁体   中英

How to get spark instance on using Primus middleware

I have setup a Primus websocket service as below.

http = require('http');
server = http.createServer();

Primus = require('primus');
primus = new Primus(server, {
  transformer: 'websockets',
  pathname: 'ws'
});

primus.on('connection', function connection(spark) {
  console.log("client has connected");
  spark.write("Herro Client, I am Server");
  spark.on('data', function(data) {
    console.log('PRINTED FROM SERVER:', data);
    spark.write('receive '+data)
  });
  spark.on('error', function(data) {
    console.log('PRINTED FROM SERVER:', data);
    spark.write('receive '+data)
  });
});



server.listen(5431);
console.log("Server has started listening");

It works fine. In above code, I use spark.write to send response message to users. Now I want to convert it to be used in a middleware. The code becomes as below:

primus.use('name', function (req, res, next) {
  doStuff();
});

in the doStuff() method, how I can get the spark instance to send message back to clients?

The readme is slightly vague about this, but middleware only deals with the HTTP request.

Primus has two ways of extending the functionality. We have plugins but also support middleware. And there is an important difference between these. The middleware layers allows you to modify the incoming requests before they are passed in to the transformers. Plugins allow you to modify and interact with the sparks. The middleware layer is only run for the requests that are handled by Primus.

To achieve what you want, you'll have to create a plugin. It's not much more complicated than middleware.

primus.plugin('herro', {
  server: function(primus, options) {
    primus.on('connection', function(spark) {
      spark.write('Herro Client, I am Server')
    })
  },
  client: function(primus, options) {}
})  

For more info, see the Plugins section of the readme.

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