A
A
Aren Proger2020-12-27 15:21:27
Angular
Aren Proger, 2020-12-27 15:21:27

Events not listening in socket.io and socket.io-client communication, Nodejs, Angular?

Hello. Code I wrote - Server.js

const app = require('express');
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const Redis = require('ioredis');
const redis = new Redis();

// Не дает реакции
io.on('connection', () => {
   console.log('New connection event');
});

// Redis прослушивает событие из Laravel, работает нормально
redis.subscribe('onlineschool_database_chat-new-message');
redis.on('message', function(channel, message){
    message = JSON.parse(message);
    // дело доходит что нужно эмитить это в клиент, нечего неработает и on connected тоже
    io.emit('newmessageevent', message.data.message);
});

// РАБОТАЕТ
server.listen(3200, function(){
   console.log('Listening 3200');
});


And here is the client side (Angular 11)

Service

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
// import Echo from 'laravel-echo';

import {Observable} from "rxjs";
import {GlobalConstants} from "../../classes/Auth/global-constants";

@Injectable({
  providedIn: 'root'
})
export class WebSocketService {
  public socket: any;
// http://127.0.0.1:3200, ws://127.0.0.1:3200, 127.0.0.1:3200
// пробовал разными способами
  public readonly web_socket_url: string = GlobalConstants.WEBSOCKET_URL;

  constructor() {

    const options = {
      rememberUpgrade:true,
      transports: ['websocket'],
      secure:true,
      rejectUnauthorized: false,
      reconnect: true
    }

    this.socket = io(this.web_socket_url, options);
  }

  listen(eventName: string) {
    console.log('connect');
    return new Observable((subscriber) => {
      this.socket.on(eventName, (data: any) => {

        subscriber.next(data);
      })
    })
  }


Call to app.component
this.WebSocket.listen('connect').subscribe((data) => {
    console.log(data);
  },
  error => console.log(error)
)

this.WebSocket.listen('disconnect').subscribe((data) => {
    console.log('Socket disconnect - ' + data);
  },
  error => console.log('Socket disconnect')
)

this.WebSocket.listen('newmessageevent').subscribe((data) => {
    console.log(data);
  },
  error => console.log(error)
)


And that's the problem, only the disconnect event works in angular when I turn off the node script, all the other emit, on, different events, the client does not see it, it feels like on, emit do nothing at all, maybe someone knows?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Shcherbina, 2021-11-08
@Denis_maker

Hello, did you find a solution to the problem? I have the same question:
https://qna.habr.com/questionversion?question_id=1...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question