Back to Blog

WebSocket Stream Mode: Real-time Data Push Made Simple

2026-03-13 5 min read

When building real-time applications, WebSocket is essential. But traditional mock tools can only respond passively - they can't simulate server-initiated pushes.

Today, MockAPI adds WebSocket Stream Mode, making it easy to simulate real-time data streams.

Why Stream Mode?

Imagine these scenarios:

  • 📈 Real-time stock prices
  • 🎮 Game state synchronization
  • 📊 Monitoring dashboard data
  • 💬 Chat message pushes
  • 📡 IoT device status updates

Traditional WebSocket Mock only does: receive message → return response. But real scenarios often involve servers actively pushing data while clients just listen.

Stream Mode solves this problem.

Features

📡 Fixed Interval Push

Set a fixed push interval, like every 1 second.

🎲 Random Delay Push

Set min and max delays to simulate real network variation.

🔄 Loop Mode

After all messages are sent, automatically restart from the beginning.

📝 JSON Auto-wrap

Non-JSON messages are automatically wrapped with metadata:

{"data": "your message", "index": 0, "timestamp": 1710345600}

💾 Persistent Storage

All WebSocket handlers are saved to config file, restored on restart.

Quick Start

  1. Start MockAPI: mockapi serve
  2. Open Web UI: http://localhost:8088/_ui
  3. Switch to WebSocket tab
  4. Click "+ Add WS Handler"
  5. Select "Stream Mode"
  6. Enter message list (one per line)
  7. Configure interval and format
  8. Save!

Example: Stock Prices

Simulating Apple stock price updates:

{"symbol": "AAPL", "price": 178.52, "change": 1.23}
{"symbol": "AAPL", "price": 178.67, "change": 1.38}
{"symbol": "AAPL", "price": 178.45, "change": 1.16}
{"symbol": "AAPL", "price": 178.89, "change": 1.60}

Configuration:

  • Interval Type: Random
  • Min Delay: 500ms
  • Max Delay: 2000ms
  • Loop: ✅

Connect to ws://localhost:8088/ws/stocks and watch prices update!

Stream vs Reply Mode

FeatureReply ModeStream Mode
TriggerClient sends messageServer pushes actively
Use CaseRequest-responseReal-time data stream
Script Support✅ JavaScript
Auto Reply

How It Works

Stream Mode uses a background goroutine that:

  1. Iterates through message list
  2. Calculates delay (fixed or random)
  3. Formats message (JSON or raw)
  4. Sends via WebSocket
  5. Detects disconnect, stops automatically

When client disconnects, goroutine cleans up automatically - no resource leaks.

Summary

WebSocket Stream Mode lets MockAPI simulate more real-world scenarios:

  • ✅ No coding required, configure via UI
  • ✅ Fixed or random intervals
  • ✅ Loop mode for continuous simulation
  • ✅ Auto-reconnect, persistent config

Try it now: go install github.com/fynntang/MockAPI@latest

Happy Streaming! 📡🦞

enzh-hans