首页 > 解决方案 > 与角度的套接字连接不起作用

问题描述

我正在尝试使用带有 Angular 和 node.js 作为后端应用程序的套接字创建一个应用程序。在后端,我可以看到连接正在建立/断开但无法读取事件。

这是我的服务器端node.js代码:

const server = require("http").createServer();
const io = require("socket.io")(server);
io.on("connection", (client) => {
  //console.log(client);
  client.emit("message", "hellow world");
  client.on("message", (data) => {
    console.log(data);
    client.emit("message", "hellow world");
  });
  client.on("disconnect", () => {});
});
server.listen(3000);

这是我在Angular代码库中添加的服务文件:

import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { io, Socket } from "socket.io-client";

@Injectable()
export class ChatService {
  private socket: Socket;

  constructor() {
    this.socket = io("http://127.0.0.1:3000");
    this.socket.on("connect", function () {
      console.log("Connected!");
    });
  }

  // EMITTER
  sendMessage(msg: string) {
    // this.socket.connect();
    console.log(this.socket);
    this.socket.emit("message", { message: msg });
  }

  // HANDLER
  onNewMessage() {
    return new Observable((observer) => {
      this.socket.on("message", (msg) => {
        console.log(msg);
        observer.next(msg);
      });
    });
  }
}

在记录 this.socket 时,我可以看到以下对象:

acks: {}
connected: false
disconnected: true
flags: {}
ids: 0
io: Manager {nsps: {…}, subs: Array(1), opts: {…}, _reconnection: true, _reconnectionAttempts: Infinity, …}
nsp: "/"

我的代码有什么问题?先感谢您。

标签: node.jsangular

解决方案


导致问题的客户端和服务器套接字版本不同。换成两边兼容的socket版本解决了这个问题。


推荐阅读