如何在 FeathersJS 服务中使用 Socket.io?

How to use Socket.io in FeathersJS service?

我正在尝试将 Socket.io 实现到我的 Feathersjs/Angular 应用程序中,并且已经建立了前端和后端之间的通信。

我了解 app.js 中的配置将服务器设置为通过 WebSockets 进行通信,但我不了解如何在通过 feathersjs 生成的服务中使用它。

如何访问服务中的 socket.io 配置?

这是我当前有效的代码:

在 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();
  });
}));

在 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!' });
    });
  }

最常见的方法是同时使用 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);
    });
  }