如何在 node.js 中以角度使用 socket.io?

DDD*_*DDD 2 node.js socket.io angular

客户端我使用 Angular 6,服务器端我使用 node.js。

在 angular 6 控制台中,它会socket.io id({message: "Hello World", id: "6An-ctwlwbZZWrfMAAAB"}) 在使用以下代码后打印消息 。

此代码是正确的或此代码中的任何更改 bcoz 我不确定此代码,请帮助纠正此问题。

另一个问题是我的项目中有超过 15 个组件,所以如何将它socket.io用于所有组件,或者我必须app.component.ts在所有其他组件中导入此代码。

app.js(服务器端)

after installing (npm i socket.io)

const express = require('express');
var app = express();
const http = require('http');
const socketIo = require('socket.io');
const server = http.Server(app);
const io = socketIo(server);

server.listen(3000,function(req,res){
  console.log("listen at 3000!");
});

io.on('connection',(socket) => {
  socket.emit('hello',{
    message : 'Hello World',id: socket.id
  })
});
Run Code Online (Sandbox Code Playgroud)

app.component.ts(客户端)

after installing (npm i socket.io)

import * as socketIo from 'socket.io-client';

export class AppComponent implements OnInit {
  ngOnInit(){
    const socket = socketIo('http://localhost:3000/');
      socket.on('hello',(data) => console.log(data));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

pra*_*nde 7

实现这种机制的一种方法是使用ngx-socket-io,在模块级别或根级别连接您的节点服务器,我已经实现如下

app.module.ts 代码

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
import { AppComponent } from './app.component';
const config: SocketIoConfig = { url: 'http://192.168.1.187:9301', options: {}  };
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config),
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

创建一项处理传入和传出流量的服务。

import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
@Injectable({
  providedIn: 'root'
})
export class SocketService {

  constructor(public socket: Socket) { }
  getMessage() {
    return this.socket
        .fromEvent<any>('msg')
        .map(data => data.msg);
}

sendMessage(msg: string) {
    this.socket.emit('msg', msg);
}
}
Run Code Online (Sandbox Code Playgroud)

更新组件文件中的代码

export class AppComponent implements OnInit {
  constructor(private socketService: SocketService) {}
  title = 'app';
  incomingmsg = [];
  msg = 'First Protocol';
  ngOnInit() {
    this.socketService
        .getMessage()
        .subscribe(msg => {
          console.log('Incoming msg', msg);
        });
        this.sendMsg(this.msg);
  }
  sendMsg(msg) {
    console.log('sdsd', msg);
    this.socketService.sendMessage(msg);
 }
}
Run Code Online (Sandbox Code Playgroud)