0

I had asked this question before but here's a simple code for the same. Im sending the data to Node from angular via websocket but I don't get the emitted event: I've followed 10+ tutorials and forums, newest from here: https://www.youtube.com/watch?v=66T2A2dvplY&t=317s

service:

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

@Injectable({
    providedIn: 'root'
})
export class SocketService {
    socket = io('ws://localhost:3000');    // adding 'http://localhost:3000' also doesnt work
    constructor() {}

    listen(eventName: string) {
        return new Observable( subscriber => {
            this.socket.on(eventName, data => {
                subscriber.next(data);
            });
        });
    }

    emit(eventName: string, data) {
        this.socket.emit(eventName, data);
    }
}

from component's ngOnInit(), this is called:

this._socketService.listen('test event').subscribe( data => {
      console.log("data from server: ", data);
});

server code of Node:

const app = require('./app');
const port = process.env.PORT || 3000;
const server = require('http').createServer(app);


const socketio = require('socket.io');
const io = socketio(server, 
  {
    serveClient: true,
    pingInterval: 60000,
    pingTimeout: 60000000,
    cors: {
      origin: "http://localhost:4200",
      methods: ["GET", "POST"],
      credentials: true
    }
});

io.on('connection', function (socket) {
  console.log("A user connected ", socket.connected);             // works till here for every ping interval
  socket.emit('test event', 'here is some data');     // this is either not executed or doesn't work
});

server.listen(port);

socket.connected is always true in NODE server, but false in Angular

What Ive tried:

  • CORS has been suppressed, I hope that's not the issue cuz nothing is seen like so

  • changing io.('connection' ...) to io.connect('connect'...)

  • init this.socket = io(...) in constructor

  • There is no data exchange seen in Network or Network > WS tab in case I emit from Angular too

  • This is my 3rd day with this problem, I'll highly appreciate any help.

Thank you

BhaskerYadav
  • 569
  • 3
  • 24
Pratik Agarwal
  • 300
  • 4
  • 16
  • Have you tried moving the assignment into the `constructor`? `constructor() { this.socket = io(...) }` [See this answer for more info](https://stackoverflow.com/questions/38269083/declare-a-class-property-outside-of-a-class-method) – Jake Holzinger Dec 24 '20 at 23:40
  • @JakeHolzinger yes I did. same thing. also tries in Node server from ```io.('connection', ...)``` to ```io.('connect', ...)``` the connection status in Node server ```socket.connected``` is ```true``` but it is false from Angular – Pratik Agarwal Dec 24 '20 at 23:50

1 Answers1

0

your mixing protocols from client.

change

socket = io('ws://localhost:3000');

to

socket = io('http://localhost:3000', { withCredentials: true });

As mentioned in introduction under chapter What Socket.IO is not that socket.io is not a pure WS lib.

Lucho
  • 1,455
  • 1
  • 13
  • 25
  • OP states in the code that this doesn't work. – Dave Newton Dec 25 '20 at 22:01
  • @DaveNewton ah, thanks. Missed that comment from phone. – Lucho Dec 25 '20 at 22:32
  • @Lucho it didnt work. maybe something else, whenever I do ```console.log(this.socket.emit(eventName, data))``` I get this Socket object with sendBuffer array and ```connected: false, disconnected: true``` ``` connected: false disconnected: true io: Manager {nsps: {…}, subs: Array(1), opts: {…}, _reconnection: true, _reconnectionAttempts: Infinity, …} nsp: "/" receiveBuffer: [] sendBuffer: Array(2) 0: data: (2) ["test event", {…}] options: {compress: true} type: 2 1: data: Array(2) 0: "test event" 1: {message: "hello server"} length: 2 options: {compress: true} type: 2 ``` – Pratik Agarwal Dec 26 '20 at 15:09