Search code examples
angularexpresswebsocketsocket.iofeathersjs

How to use Socket.io in FeathersJS service?


I am trying to implement Socket.io into my Feathersjs/Angular application and have established the communication between the front and back ends.

I understand that the configuration in app.js sets up the server to communicate via WebSockets, but I am not understanding how to use it within a Service that is generated via feathersjs.

How can I access the socket.io configuration within the service?

Here is my current code that works:

on the server in app.js

// Set up Plugins and providers
app.configure(express.rest());
app.configure(socketio(function(io) {
  io.on('connection', function(socket) {
    socket.emit('backend-notification', { text: 'A client connected!' });
    socket.on('frontend-notification', function (data) {
      console.log(data);
    });
  });

  // Registering Socket.io middleware
  io.use(function (socket, next) {
    // Exposing a request property to services and hooks
    socket.feathers.referrer = socket.request.referrer;
    next();
  });
}));

on the frontend in app.component.ts

ngOnInit(): void {
    const socket = socketIo('http://localhost:3000');

    socket.on('backend-notification', (data) => {
      console.log(data);
      socket.emit('frontend-notification', { text: 'My frontend-notification!' });
    });
  }

Solution

  • The most common way is to also use Feathers on the client which allows you to transparently access the services on the server. The direct usage of services via a websocket is documented in the direct connection API for Socket.io:

    ngOnInit(): void {
        const socket = socketIo('http://localhost:3000');
    
        socket.on('message create', (message) => {
          console.log('New message created', message);
        });
    
        socket.emit('create', 'message', {
          text: 'This is a new message'
        }, (error, message) => {
          console.log('New message created via socket', message);
        });
      }