首页 > 解决方案 > 对 Node 后端/Angular 前端中的 socket.io 事件系统进行故障排除

问题描述

我需要在 Node 后端设置一个简单的事件系统,以在某些事件发生时通知客户端(Angular 应用程序)(当用户更改他的个人资料照片时)。我在后端使用 socket.io 库,在前端使用等效的“ngx-socket-io”。这是我到目前为止所做的:

后端 - 'bin/www'(服务器初始脚本)

// 'server' is created using 'http.createServer()'
const io = require('socket.io')(server);

// Set the socket.io object in the main app object to access it from anywhere
app.set('socketio', io);

io.on('connection', socket => {
    logger.debug('Socket connected: ', socket.id);

    socket.on('disconnect', () => {
        logger.debug('Socket disconnected: ', socket.id);
    });
});

后端 - 'controllers/user.js'(用户路由控制器)

controller.changeProfilePhoto = function(req, res) {        
    // Socket IO object
    const socketio = req.app.get('socketio');

    // Do the stuff to change the profile photo...

    if(socketio) {
        socketio.emit("appevent", { msg: 'Profile photo updated', user: req.body.userId });
    }
}

前端 - 'services/app-events.service.ts'(应用事件服务)

import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AppEventsService {

  constructor(private socket: Socket) { }

  sendMessage(msg: string) {
    this.socket.emit("appevent", msg);
  }

  getMessage(): Observable<any> {
    return this.socket.fromEvent("appevent");
  }
}

我订阅了getMessage在发生某些事件时需要更新的组件,但我没有收到任何事件。在后端,每次客户端连接时我都会看到一条消息:

套接字连接:Wv8-DXqMaPi_dhRIAAAA

有什么问题?

提前致谢!

标签: node.jsangularsocket.io

解决方案


该问题与 socket.io 无关,而是与从客户端到达后端的方式有关。我正在使用反向代理来避免在防火墙中为 API 打开额外的端口,并且我在 socket.io 连接中使用了错误的 URL。

如果有人需要它,这是proxy.conf.json我正在使用的文件:

{
    "/api": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug",
        "pathRewrite": {
            "^/api": ""
        }
    },
    "/socket.io": {
        "target": "http://localhost:3000",
        "secure": false,
        "logLevel": "debug",
        "ws": true
    }
}

socket.io 连接的 URL 必须是客户端的基地址,如下例所示:

希望有帮助,加油!


推荐阅读