angular / nest js scoket io中无法在所有客户端接收数据。
创始人
2024-10-15 05:01:31
0

要在所有客户端接收数据,您可以使用Angular和NestJS中的Socket.IO来实现实时通信。下面是一个示例代码,展示了如何在Angular和NestJS之间进行Socket.IO通信。

首先,在NestJS中创建一个WebSocket模块,用于处理Socket.IO连接和事件:

// src/websocket/websocket.module.ts

import { Module } from '@nestjs/common';
import { SocketGateway } from './socket.gateway';

@Module({
  providers: [SocketGateway],
})
export class WebSocketModule {}
// src/websocket/socket.gateway.ts

import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server } from 'socket.io';

@WebSocketGateway()
export class SocketGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('message')
  handleMessage(client: any, payload: any): void {
    this.server.emit('message', payload); // 向所有客户端发送消息
  }
}

然后,创建一个Angular服务来处理与NestJS的Socket.IO通信:

// src/app/socket.service.ts

import { Injectable } from '@angular/core';
import { io, Socket } from 'socket.io-client';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SocketService {
  private socket: Socket;

  constructor() {
    this.socket = io('http://localhost:3000'); // 与NestJS服务器建立Socket.IO连接
  }

  sendMessage(message: string): void {
    this.socket.emit('message', message);
  }

  getMessage(): Observable {
    return new Observable((observer) => {
      this.socket.on('message', (data: string) => {
        observer.next(data); // 接收来自服务器的消息
      });
    });
  }
}

最后,在Angular组件中使用SocketService来发送和接收消息:

// src/app/app.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { SocketService } from './socket.service';

@Component({
  selector: 'app-root',
  template: `
    
{{ msg }}
`, }) export class AppComponent implements OnInit, OnDestroy { message: string; messages: string[] = []; private subscription: Subscription; constructor(private socketService: SocketService) {} ngOnInit(): void { this.subscription = this.socketService .getMessage() .subscribe((message: string) => { this.messages.push(message); // 接收来自服务器的消息并添加到消息数组中 }); } ngOnDestroy(): void { this.subscription.unsubscribe(); } sendMessage(): void { this.socketService.sendMessage(this.message); // 发送消息到服务器 this.message = ''; } }

确保在NestJS中启用WebSocket模块,并在Angular中提供SocketService:

// src/main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SocketAdapter } from './websocket/socket.adapter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new SocketAdapter(app));
  await app.listen(3000);
}
bootstrap();
// src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { WebSocketModule } from './websocket/websocket.module';

@Module({
  imports: [WebSocketModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

以上就是一个基本的示例,可以让所有客户端接收数据。您可以根据自己的需求进行修改和扩展。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...