简体   繁体   中英

Socket.io not working on Angular4

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM