node.js - 与角度的套接字连接不起作用
问题描述
我正在尝试使用带有 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: "/"
我的代码有什么问题?先感谢您。
解决方案
导致问题的客户端和服务器套接字版本不同。换成两边兼容的socket版本解决了这个问题。
推荐阅读
- javascript - 如何知道 JavaScript 中哪个函数调用了另一个函数?
- clojure - 带有基座 clojure 服务器的通用 [/*proxy :any] 和特定 [/service/x :post..] 路由
- html - 将 css 属性分配给父级,而不是子级
- javascript - JavaScript - 在同一窗口/选项卡中打开链接
- sql-server - 使用 sql server 将数字从 002541500(后 4 位为小数位)转换为 254.1500
- xml - 简单转换反序列化:匹配元素错误
- speech-recognition - 如何在 dictation.io/speech 中捕捉/精确文本
- php - 如何使用 Laravel 5.* 获取数据类型的绑定
- php - 在布尔值中调用成员函数 getTimestamp()
- c# - 如何使用 C# 字典从 Dapper 中的银行映射 JSON?