我正在尝试通过以下链接通过羽毛 js + primus 设置 websocket:https ://docs.feathersjs.com/real-time/primus.html 。但我不知道如何从服务器端的 primus 获取 spark 实例。下面是我的服务器代码:
class SocketService {
create(data, params, callback){
...
}
}
module.exports = function(){
const app = this
let ss = new SocketService()
app.use('socket-shell', ss);
}
在上面的代码中,服务器可以在 create() 方法中从客户端获取消息。但是我怎样才能在那个方法中从 primus 获取 spark 实例呢?我想使用spark.write
方法将消息发送回客户端。
下面是配置羽毛服务的服务器代码:
app
.use(compress())
.options('*', cors())
.use(cors())
// .use(favicon(path.join(app.get('public'), 'favicon.ico')))
.use('/', serveStatic(app.get('public')))
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: true}))
.configure(hooks())
.configure(rest())
.configure(primus({
transformer: 'websockets',
timeout: false,
}, (primus) => {
app.use('socket-shell', function(socket, done){
// Exposing a request property to services and hooks
socket.request.feathers.referrer = socket.request.referrer;
done();
});
}))
.configure(services)
.configure(middleware);
以下代码用于在服务器端注册事件侦听器,但无法接收来自客户端的事件:
class SocketService {
constructor(options) {
this.events = [ 'someevent','serverevent' ]
}
setup(app) {
this.app = app;
let socketService = app.service('socket-shell')
socketService.addListener('serverevent', this.serverevent)
}
serverevent(msg){
console.log('serverevent', msg)
}
在客户端代码中,我使用以下代码向服务器发送消息:
var primus = new Primus('http://localhost:3030');
var app = feathers()
.configure(feathers.hooks())
.configure(feathers.primus(primus));
var messageService = app.service('/socket-shell');
messageService.emit('serverevent', {msg:'this is client'})
上面的代码有什么问题?