我已经设置了一个 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");
它工作正常。在上面的代码中,我用来spark.write
向用户发送响应消息。现在我想将它转换为在中间件中使用。代码变成如下:
primus.use('name', function (req, res, next) {
doStuff();
});
在 doStuff() 方法中,如何让 spark 实例将消息发送回客户端?