简体   繁体   English

如何使用Primus中间件获取Spark实例

[英]How to get spark instance on using Primus middleware

I have setup a Primus websocket service as below. 我已经如下设置了Primus websocket服务。

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. 在上面的代码中,我使用spark.write向用户发送响应消息。 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? 在doStuff()方法中,如何获取spark实例以将消息发送回客户端?

The readme is slightly vague about this, but middleware only deals with the HTTP request. 自述文件对此有些含糊,但中间件仅处理HTTP请求。

Primus has two ways of extending the functionality. Primus有两种扩展功能的方式。 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. 中间件层仅针对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. 有关更多信息,请参见自述文件的“ 插件”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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