简体   繁体   中英

How to use feathersjs-primus to setup websocket connection

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:

  • Set up and send your own events in app.configure(primus(
  • Have the service emit its own custom events

--

class SocketService {
  constructor() {
    this.events = [ 'someevent' ];
  }

  create(data, params, callback){
      this.emit('someevent', 'data');
  }
}

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