【问题标题】:How to use Socket.io in FeathersJS service?如何在 FeathersJS 服务中使用 Socket.io?
【发布时间】:2018-10-25 16:38:09
【问题描述】:

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

我了解 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!' });
    });
  }

【问题讨论】:

    标签: angular express websocket socket.io feathersjs


    【解决方案1】:

    最常用的方法是也使用Feathers on the client,它允许您透明地访问服务器上的服务。通过websocket直接使用服务是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);
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      相关资源
      最近更新 更多