0

I am build a project with Angular and Express and I want to integrate Socket.io for a chat. The problem is that it doesn't seem to be working at all. I ran the command

npm install socket.io --save

And this is my Express index.js file:

// Define variables
const express = require('express');
const app = express();
var http = require('http');
var server = http.createServer(app);


var io = require('socket.io').listen(server);

io.on('connection',(socket)=>{
    console.log("User connected");
});


// Use the /dist directory
app.use(express.static(__dirname + '/dist'));

// Catch all other invalid routes
app.all('*', function(req,res){
    res.status(200).sendFile(__dirname + '/dist/index.html');
});

// Start the server
app.listen(3000, function(){
  console.log('listening on *:3000');
});

It doesn't even console log "User connected". This is the code on the Angular component where I call the Socket:

import { Component, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { UsuariosService } from '../../services/usuarios.service';
import { Usuario } from '../registro/usuario';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Mensaje } from './mensaje';
import * as io from 'socket.io-client';

@Component({
    selector: 'chat',
    templateUrl: './chat.component.html',
    providers: [UsuariosService]
})
export class ChatComponent{

    public usuario:Usuario;
    public amigo:Usuario;
    public mensajes:Mensaje[];
    public texto:string;
    private socket;

    constructor(
        public dialogRef: MatDialogRef<ChatComponent>,
        @Inject(MAT_DIALOG_DATA) public data: any,
        private _usuariosService: UsuariosService,
        public snackBar:MatSnackBar,
        public _router:Router,
    ){
        this.usuario = data.usuario;
        this.amigo = data.amigo;
        this.mensajes = new Array();
        this.texto = "";
        this.socket = io();
    }
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
  • I hope this could help https://stackoverflow.com/questions/47161589/how-to-use-socket-io-client-in-angular-4/47162212#47162212 – VithuBati May 28 '18 at 15:07

1 Answers1

0

You must install npm install socket.io-client npm install @types/socket.io-client and apart from that you must initialize this.socket = io(environment.ws_url) where this.socket = environment.ws_url it s mean your endpoint of websocket or use socket = new WebSocket(environment.ws_url) and use this.socket.onmessage = (me: any) => { const data = JSON.parse(me.data); this.files.push(data); }; `

Regards