[英]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. 我正在使用Angular和Express构建一个项目,并且希望集成Socket.io进行聊天。 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: 这是我的Express index.js文件:
// 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:
这是我称之为Socket的Angular组件上的代码:
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); 您必须安装npm install socket.io-client npm install @ types / socket.io-client,除此之外,您还必须初始化this.socket = io(environment.ws_url),其中this.socket = environment.ws_url表示您的端点websocket或使用socket = new WebSocket(environment.ws_url)并使用this.socket.onmessage =(me:any)=> {const data = JSON.parse(me.data); this.files.push(data);
this.files.push(data); };
}; `
`
Regards 问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.