簡體   English   中英

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

[英]How to use socket.io in angular with node.js?

客戶端我使用 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
  })
});

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

實現這種機制的一種方法是使用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 { }

創建一項處理傳入和傳出流量的服務。

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

更新組件文件中的代碼

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

創建服務並將您的套接字數據轉換為 Observable 流

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/behaviorSubject';  
import { Observer } from 'rxjs/Observer';
import { Observable } from 'rxjs/Observable';
import * as Rx from 'rxjs';
import * as io from 'socket.io-client';

@Injectable()
export class ChatService {

  observable: Observable<string>;
  socket;

  constructor() {
    this.socket = io('http://localhost:3000');     
   }

   getData(): Observable<string> {
    return this.observable = new Observable((observer) => 
      this.socket.on('hello', (data) => observer.next(data))
    );
  }

  // This one is for send data from angular to node 
  pushData(e) {
    this.socket.emit('hello', e);
  }
}

然后從組件調用

App.component.ts

import { Component } from '@angular/core';
import { ChatService } from './common/chat.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {  
  title;
  chat;
  constructor(private cService: ChatService) {
    this.cService.getData().subscribe(data => console.log(data));
  }

  onClick(e: string) {
    this.cService.pushData(e);
    this.chat = '';
  }
}

您可以創建用於使用套接字的服務。 例如(當然這是一個非常簡單的例子):

/* e.g app/shared/io/io.service.ts */

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

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

const SERVER_URL = '/';

/** Your events enum */
export enum IOEventName {
    EVENT_NAME_1 = "EVENT_NAME_1",
    EVENT_NAME_2 = "EVENT_NAME_2",
    ...
}

/** Interfaces for your event messages */
export interface IEventName1Message {
    propOne: number,
    propTwo: string,
    ...
}

export interface IEventName2Message {
    propOne: Date,
    propTwo: Boolean,
    ...
}
...

@Injectable()
export class SocketService {
    private socket: SocketIOClient.Socket;

    public initSocket(): void {
        this.socket = socketIo(SERVER_URL);
    }

    public onEvent<T>(event: IOEventName): Observable<T | Array<T>> {
        return new Observable<T>(observer => {
            this.socket.on(event, (data: T) => observer.next(data));
        });
    }

    public destroy() {
        if (this.socket) {
            this.socket.removeAllListeners();
            this.socket.close();
            this.socket = undefined;
        }
    }
}

並在任何組件中使用它:

import { SocketService, IOEventName, IEventName1Message, IEventName2Message } 
    from 'app/shared/io/io.service';

export class AppComponent implements OnInit, OnDestroy {
    constructor(private socketService: SocketService) { }

    ngOnInit() {
        this.socketService.initSocket();
        this.socketService
            .onEvent<IEventName1Message>(IOEventName.EVENT_NAME_1)
            .subscribe(data => { /* message received */ });

        this.socketService
            .onEvent<IEventName2Message>(IOEventName.EVENT_NAME_2)
            .subscribe(data => { /* message received */ });
    }

    ngOnDestroy() {
        this.socketService.destroy();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM