1

I am trying to create an application using socket with Angular and node.js as backend application. In the backend I can see that connection is getting established/disconnected but not able to read events.

this is my server side node.js code:

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);

this is my service file added in Angular codebase:

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

While logging this.socket, i can see the following object:

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

Whats wrong with my code? Thank you in advance.

5
  • Why you didnt' ngx-socket-io instead of socket.io-client is more dedicated for angular project , techiediaries.com/… Commented Apr 23, 2021 at 9:54
  • @RebaiAhmed: I used that also, that was also having the same issue. Commented Apr 24, 2021 at 13:48
  • error by the varsion differance Commented Apr 25, 2021 at 4:51
  • You mean version difference ? Commented Apr 25, 2021 at 10:19
  • Hi @Era did you solved it ? Commented Apr 30, 2021 at 8:07

2 Answers 2

2

The client and server socket versions were different which was causing the issue. Changing to the compatible socket version at both the sides solved the problem.

Sign up to request clarification or add additional context in comments.

Comments

-1

use socket-io-client with version 2.3.1 and try.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.