0Pricing
Node.js Backend Development Bootcamp · Ders

Ağ Geçidi Yapılandırması

NestJS'te WebSocket ağ geçitlerini yapılandırın; bağlantı olaylarını, iletileri ve oda yönetimini işleyin.

Ağ Geçidi Yapılandırması, CoddyKit'te ücretsiz bir Node.js Backend Development Bootcamp dersidir. Bu, 6 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Node.js Backend Development Bootcamp öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Node.js Backend Development Bootcamp kursu toplamda 6 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Unlocking Real-time with Gateways

Welcome back! In the previous lesson, we learned about WebSockets. Now, let's dive into how NestJS makes real-time communication easy with Gateways.

Think of a Gateway as a special controller for WebSocket connections. It listens for messages from clients and sends responses back, enabling dynamic, two-way communication.

Creating Your First Gateway

To create a Gateway, we use the @WebSocketGateway() decorator. This decorator marks a class as a WebSocket gateway.

By default, NestJS uses Socket.IO. You can specify a port, namespace, or other options. Let's start with a basic gateway:

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

// src/events.gateway.ts
@WebSocketGateway(3001) // Listens on port 3001 for WS
export class EventsGateway {
  @WebSocketServer() server: Server;
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000); // HTTP app, WS runs alongside
}
bootstrap();

Gateway Configuration Options

The @WebSocketGateway() decorator accepts an optional configuration object. This lets you customize how your WebSocket server behaves:

  • port: The port the WebSocket server listens on (e.g., 3001).
  • namespace: Group connections under a specific path (e.g., '/chat').
  • cors: Configure Cross-Origin Resource Sharing for browser clients.
  • adapter: Specify a custom WebSocket adapter (e.g., for `ws` instead of `socket.io`).

Handling Connections & Disconnections

Gateways can react to client connections and disconnections using lifecycle hooks. These are interfaces your gateway can implement:

  • OnGatewayInit: Called once the gateway is initialized.
  • OnGatewayConnection: Called when a client connects.
  • OnGatewayDisconnect: Called when a client disconnects.

Use these to perform setup or cleanup tasks.

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway
  implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;

  handleConnection(client: Socket, ...args: any[]) {
    console.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    console.log(`Client disconnected: ${client.id}`);
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Subscribing to Client Messages

Clients send messages with an 'event name'. Your gateway listens for these specific events using the @SubscribeMessage() decorator.

The decorated method receives the client (Socket instance) and the payload (data sent by the client).

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('sendMessage')
  handleMessage(client: Socket, payload: string): void {
    console.log(`Message from ${client.id}: ${payload}`);
    // Process payload, then send response
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Sending Messages Back to Clients

Once your gateway receives a message, you'll often want to send a response. You can inject the WebSocketServer instance using @WebSocketServer().

To send a message to a specific client, use client.emit('eventName', data). To broadcast to all clients, use this.server.emit('eventName', data).

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('echo')
  handleEcho(client: Socket, payload: string): void {
    console.log(`Received: ${payload} from ${client.id}`);
    client.emit('echoResponse', `You said: ${payload}`);
  }

  @SubscribeMessage('broadcast')
  handleBroadcast(client: Socket, payload: string): void {
    this.server.emit(
      'broadcastMessage', 
      `${client.id} broadcasted: ${payload}`
    );
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Organizing Clients with Rooms

For more complex applications, you might not want to broadcast every message to every client. This is where rooms come in handy!

Rooms allow you to group specific clients together. Messages can then be sent only to clients within a particular room. This is perfect for chat channels, game lobbies, or specific user notifications.

Joining and Leaving Rooms

Socket.IO clients can join or leave rooms dynamically. You can manage this from your gateway methods using the client instance:

  • client.join(roomName): Adds the client to the specified room.
  • client.leave(roomName): Removes the client from the specified room.

A client can be in multiple rooms simultaneously.

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('joinRoom')
  handleJoinRoom(client: Socket, room: string): void {
    client.join(room);
    client.emit('joinedRoom', `You joined ${room}`);
    console.log(`${client.id} joined room: ${room}`);
  }

  @SubscribeMessage('leaveRoom')
  handleLeaveRoom(client: Socket, room: string): void {
    client.leave(room);
    client.emit('leftRoom', `You left ${room}`);
    console.log(`${client.id} left room: ${room}`);
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Sending Messages to Specific Rooms

Once clients are in rooms, you can send targeted messages. Use the server.to(roomName).emit('eventName', data) method.

This ensures only clients subscribed to that particular room receive the message, making your real-time updates efficient and relevant.

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('roomMessage')
  handleRoomMessage(
    client: Socket,
    payload: { room: string; message: string },
  ): void {
    const { room, message } = payload;
    this.server
      .to(room)
      .emit('roomUpdate',
            `[${room}] ${client.id}: ${message}`);
    console.log(
      `Message in ${room} from ${client.id}: ${message}`
    );
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Gateway Configuration Quiz

Which of the following statements about NestJS WebSocket Gateways and rooms are TRUE?

Recap: Master Your Gateway

Great job! You've learned how to configure NestJS Gateways for powerful real-time communication.

  • We defined gateways using @WebSocketGateway().
  • We explored configuration options like port and namespace.
  • We implemented lifecycle hooks for connections and disconnections.
  • We handled client messages with @SubscribeMessage().
  • We used @WebSocketServer() to broadcast and send targeted messages.
  • Finally, we mastered rooms for efficient client grouping and targeted messaging.

Next, we'll build a full real-time chat application!

Sıkça Sorulan Sorular

“Ağ Geçidi Yapılandırması” dersi ücretsiz mi?

Evet — “Ağ Geçidi Yapılandırması” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Node.js Backend Development Bootcamp kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Node.js Backend Development Bootcamp kursu toplamda 6 dersten oluşur.

“Ağ Geçidi Yapılandırması” dersinde ne öğreneceğim?

NestJS'te WebSocket ağ geçitlerini yapılandırın; bağlantı olaylarını, iletileri ve oda yönetimini işleyin. Node.js Backend Development Bootcamp ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Node.js Backend Development Bootcamp öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Node.js Backend Development Bootcamp, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 6 dersinin 4. dersidir.

“Ağ Geçidi Yapılandırması” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Node.js Backend Development Bootcamp dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Node.js Backend Development Bootcamp dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. WebSockets'e Giriş
  2. NestJS ile WebSockets
  3. Node.js'te Socket.IO Uygulama
  4. Ağ Geçidi Yapılandırması
  5. Gerçek Zamanlı Sohbet Uygulaması Geliştirme
  6. Gerçek Zamanlı Sohbet Uygulaması
← Node.js Backend Development Bootcamp Sayfasına Dön