1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【NestJS】WebsocketGatewayを作成する

Posted at

はじめに

WebsocketGatewayの理解を深めるためにサンプルソースを交えて本記事を作成しています。
参考にしたのは公式ドキュメントになります。

Client side(今回はPostman)からGatewayにアクセスされた時の挙動について触れています。
スクリーンショット 2023-02-12 12.13.21.png

実装

プロジェクト作成

nest new nestjs-websocket

パッケージをインストール

npm i --save @nestjs/websockets @nestjs/platform-socket.io

Gateways作成

プロジェクト配下のsrcフォルダに新規gatewayフォルダを作成し、フォルダ内にgateway.module.tsgateway.tsを作成する

ファイル構成
|──nestjs-websocket
| |──src
|   |──gateway
|     |──gateway.ts
|     |──gateway.module.ts
|
|   |──app.module.ts
gateway.module.ts
import { Module } from '@nestjs/common';
import { Gateway } from './gateway';

@Module({
  providers: [Gateway],
})
export class GatewayModule {}
gateway.ts
import { OnModuleInit } from '@nestjs/common';
import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server } from 'socket.io';

@WebSocketGateway()
export class Gateway implements OnModuleInit {
  @WebSocketServer()
  server: Server;

  onModuleInit() {
    this.server.on('connection', (socket) => {
      console.log(socket.id);
      console.log('connected!');
    });
  }

  @SubscribeMessage('newMessage')
  onnewMessage(@MessageBody() body: any) {
    console.log(body);
    this.server.emit('onMessage', {
      msg: 'New Message',
      content: body,
    });
  }
}
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GatewayModule } from './gateway/gateway.module';

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

Postmanでソケット通信の確認

postmanでのソケット通信の確認方法はこちらをご参考ください。

ローカルサーバー起動

npm run start

PostmanでSocket.IO接続

スクリーンショット 2023-02-12 17.43.05.png

接続が成功するとログが出力されます
出力処理しているのはgateway.tsのonModuleInitメソッドの部分

rqfA4At3AECFhrZSAAAB
connected!

イベントを発行する

スクリーンショット 2023-02-12 17.48.53.png

発行したイベント「newMessage」をgateway.tsの下記処理で受信しています

gateway.ts
  @SubscribeMessage('newMessage')
  onnewMessage(@MessageBody() body: any) {
    console.log(body);
  }

イベントを受信する

イベント「newMessage」を受信したら、イベント「onMessage」を発行する流れ

gateway.ts
@SubscribeMessage('newMessage')
  onnewMessage(@MessageBody() body: any) {
    console.log(body);
    this.server.emit('onMessage', {
      msg: 'New Message',
      content: body,
    });
  }

一連の流れを確認するために
まずは、Postmanで新しくタブを開いて受信したいイベントに「onMessage」を入力する
スクリーンショット 2023-02-12 17.57.10.png

イベント「newMessage」を発行する
スクリーンショット 2023-02-12 18.07.37.png

サーバー上でイベント「newMessage」を受信後、イベント「onMessage」が発行し、Postmanでイベントを受信する
スクリーンショット 2023-02-12 18.09.08.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?