I am trying to setup websocket by feathers js + primus following from this link: https://docs.feathersjs.com/real-time/primus.html. But I don't know how to get spark instance from primus in server side. Below is my server code:
class SocketService {
create(data, params, callback){
...
}
}
module.exports = function(){
const app = this
let ss = new SocketService()
app.use('socket-shell', ss);
}
In above code, server can get the message from client in create() method. But how can I get spark instance from primus in that method? I want to use spark.write
method to send message back to the client.
Below is the server code for configuring feathers services:
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);
Below code is used to registering a event listener on server side but it can't receive event from client:
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)
}
In client code, I use below code to emit message to server:
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'})
what wrong with above code?
Ideally you wouldn't use the socket connection directly in your service. A service shouldn't know about how it is being accessed. There are two options:
app.configure(primus(
--