websocket-setup

Hướng Dẫn Chạy API và WebSocket Server

Tổng Quan

Hệ thống được thiết kế theo mô hình Hybrid Application của NestJS:

  • API Server: Port 3001 (hoặc theo biến môi trường PORT/API_PORT)
  • WebSocket Server: Port 3002 (hoặc theo biến môi trường WS_PORT)
  • Một lệnh duy nhất: Chỉ cần chạy npm run start:dev để khởi động cả hai

Cách Chạy Hệ Thống

Development Mode:

npm run start:dev

Production Mode:

npm run start:prod

Debug Mode:

npm run start:debug

Biến Môi Trường

Thêm các biến sau vào file .env:

# API Server
PORT=3001
API_PORT=3001

# WebSocket Server
WS_PORT=3002

Kiểm Tra Trạng Thái

Sau khi chạy thành công, bạn sẽ thấy:

🚀 API Server is running on: http://localhost:3001
📋 Swagger documentation: http://localhost:3001/api
🔌 WebSocket Server will run on: http://localhost:3002
🔌 Socket.IO Support namespace: http://localhost:3002/support

Lưu Ý Quan Trọng

  1. Hybrid Application: Sử dụng một NestJS app duy nhất với multiple port listeners
  2. Database Connection: Cả HTTP và WebSocket đều kết nối đến cùng database
  3. Redis Connection: Chia sẻ cùng Redis instance cho caching và pub/sub
  4. Service Sharing: Các services được chia sẻ giữa HTTP và WebSocket (như SocketUtil)
  5. WebSocket Gateways: Tất cả WebSocket gateways đều chạy trên port 3002
    • /support - Support system
    • / - Main gateway
    • Price, DEX, Trade, Chat gateways

Cấu Hình WebSocket Gateways

Tất cả WebSocket gateways đã được cấu hình để sử dụng WS_PORT:

@WebSocketGateway({
  port: parseInt(process.env.WS_PORT || '3002', 10),
  // ... other options
})

Deploy với Docker

Dockerfile đã được cấu hình để expose cả 2 ports:

EXPOSE 3001 3002

GitLab CI/CD đã được cấu hình để map ports:

  • API: 3001:3001
  • WebSocket: 3002:3002

Troubleshooting

Port Already in Use

# Kiểm tra processes đang sử dụng ports
lsof -i :3001
lsof -i :3002

# Kill process nếu cần
kill -9 <PID>

Kiểm tra WebSocket Connection

# Test WebSocket connection với curl
curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Key: test" -H "Sec-WebSocket-Version: 13" http://localhost:3002/support

Dependencies

Đảm bảo đã install dependencies:

npm install

Architecture Summary

┌─────────────────────────────────┐
│         NestJS Application      │
├─────────────────────────────────┤
│  HTTP Server (Port 3001)        │
│  ├─ REST APIs                   │
│  ├─ Swagger Documentation       │
│  └─ Health Check                │
├─────────────────────────────────┤
│  WebSocket Server (Port 3002)   │
│  ├─ Support Gateway (/support)  │
│  ├─ Main Gateway (/)            │
│  ├─ Price Gateway               │
│  ├─ DEX Gateway                 │
│  ├─ Trade Gateway               │
│  └─ Chat Gateway                │
├─────────────────────────────────┤
│     Shared Services             │
│  ├─ Database (TypeORM)          │
│  ├─ Redis (Cache & PubSub)      │
│  ├─ SocketUtil                  │
│  └─ Other Services              │
└─────────────────────────────────┘