Skip to main content

websocket-in

Receive real-time messages over WebSocket connections.

websocket-in
input v1.0.0

Receive messages over WebSocket connections. Can act as a server (accept connections) or client (connect to server).

websocket realtime streaming bidirectional
Inputs
0
Outputs
1

Overview

The websocket-in node enables real-time bidirectional communication using the WebSocket protocol. Unlike HTTP, WebSocket connections stay open, allowing instant message delivery without polling.

  • Server mode - Create a WebSocket server for browsers and devices to connect
  • Client mode - Connect to external WebSocket servers
  • Low latency - Messages delivered in milliseconds
  • Full duplex - Send and receive simultaneously
  • Automatic reconnection - Client mode reconnects on disconnect
When to use WebSocket vs MQTT

Use WebSocket for browser dashboards and direct device communication. Use MQTT for IoT sensor networks with many devices and a central broker.

Properties

Property Type Required Default Description
name string - - Display name for this node in the editor.
mode string server Connection mode: "server" (listen for connections) or "client" (connect to server).
path string /ws WebSocket path for server mode, or full URL for client mode.
wholemsg boolean - false If true, sends the entire msg object as JSON. If false, sends only msg.payload.
hb number - 0 Heartbeat interval in seconds (0 to disable). Sends ping frames to keep connection alive.
subprotocol string - - WebSocket subprotocol to use (e.g., "mqtt", "wamp").

Server Mode

In server mode, the node creates a WebSocket endpoint on EdgeFlow. Clients (browsers, devices) can connect to receive and send messages.

Server Endpoint URL

ws://<device-ip>:1880<path>

# Example with path "/ws/sensors":
ws://192.168.1.100:1880/ws/sensors

# For secure connections (requires HTTPS):
wss://your-domain.com/ws/sensors

JavaScript Client Example

const ws = new WebSocket('ws://192.168.1.100:1880/ws/sensors');

ws.onopen = () => {
  console.log('Connected');
  ws.send(JSON.stringify({ type: 'subscribe', topic: 'temperature' }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};

ws.onerror = (error) => console.error('Error:', error);
ws.onclose = () => console.log('Disconnected');

Client Mode

In client mode, the node connects to an external WebSocket server. Use this to receive data from third-party services or other EdgeFlow instances.

Client Connection URLs

# Plain WebSocket
ws://example.com:8080/stream

# Secure WebSocket
wss://api.example.com/v1/websocket

# With authentication in URL
wss://api.example.com/stream?token=abc123

Outputs

When a message is received, the node outputs:

Output Message Format

{`{
  "payload": "message content or parsed JSON",
  "_session": {
    "type": "websocket",
    "id": "unique-session-id"
  },
  "_msgid": ""
}`}

The _session object identifies the client connection. Use this with websocket-out to send replies to specific clients.

Connection Events

Special messages are sent when clients connect or disconnect:

Event msg.payload Description
Connect { "_event": "connect" }Client connected
Disconnect { "_event": "disconnect" }Client disconnected

Examples

Real-Time Dashboard Server

Create a WebSocket server that pushes sensor updates to connected browsers.

Dashboard WebSocket Server

Receives sensor data and broadcasts to all connected dashboard clients.

View Flow JSON
[
  &#123;
    "id": "wsin1",
    "type": "websocket-in",
    "name": "Dashboard WS",
    "mode": "server",
    "path": "/ws/dashboard",
    "wholemsg": false,
    "wires": [["function1"]]
  &#125;,
  &#123;
    "id": "function1",
    "type": "function",
    "name": "Handle Messages",
    "func": "// Handle incoming client messages\nif (msg.payload._event === 'connect') &#123;\n  node.warn('Client connected: ' + msg._session.id);\n  return null;\n&#125;\n\n// Echo received messages\nreturn msg;"
  &#125;,
  &#123;
    "id": "mqtt1",
    "type": "mqtt-in",
    "name": "Sensors",
    "topic": "sensors/#",
    "wires": [["wsout1"]]
  &#125;,
  &#123;
    "id": "wsout1",
    "type": "websocket-out",
    "name": "Broadcast",
    "mode": "server",
    "path": "/ws/dashboard"
  &#125;
]

Stock Price Client

Connect to an external WebSocket API to receive real-time stock prices.

Stock Price Stream

Connects to a stock price API and processes incoming price updates.

View Flow JSON
[
  &#123;
    "id": "wsin2",
    "type": "websocket-in",
    "name": "Stock Prices",
    "mode": "client",
    "path": "wss://stream.example.com/prices",
    "wholemsg": false,
    "hb": 30,
    "wires": [["function2"]]
  &#125;,
  &#123;
    "id": "function2",
    "type": "function",
    "name": "Parse Price",
    "func": "const data = JSON.parse(msg.payload);\nmsg.payload = &#123;\n  symbol: data.s,\n  price: parseFloat(data.p),\n  timestamp: new Date(data.t)\n&#125;;\nreturn msg;",
    "wires": [["influx1", "debug1"]]
  &#125;,
  &#123;
    "id": "influx1",
    "type": "influxdb",
    "name": "Store Price",
    "measurement": "stock_prices"
  &#125;,
  &#123;
    "id": "debug1",
    "type": "debug",
    "name": "Log"
  &#125;
]

Broadcast to All Clients

Send alerts to all connected WebSocket clients when a threshold is exceeded.

Temperature Alert Broadcast

Monitors temperature and broadcasts alerts to all connected clients.

View Flow JSON
[
  &#123;
    "id": "sensor1",
    "type": "dht22",
    "name": "Temperature",
    "pin": 4,
    "wires": [["switch1"]]
  &#125;,
  &#123;
    "id": "switch1",
    "type": "switch",
    "name": "Check Threshold",
    "property": "payload.temperature",
    "rules": [&#123;"t": "gt", "v": "30"&#125;],
    "wires": [["function3"]]
  &#125;,
  &#123;
    "id": "function3",
    "type": "function",
    "name": "Format Alert",
    "func": "msg.payload = &#123;\n  type: 'alert',\n  level: 'warning',\n  message: 'High temperature: ' + msg.payload.temperature + '°C',\n  timestamp: Date.now()\n&#125;;\nreturn msg;",
    "wires": [["wsout2"]]
  &#125;,
  &#123;
    "id": "wsout2",
    "type": "websocket-out",
    "name": "Broadcast Alert",
    "mode": "server",
    "path": "/ws/alerts"
  &#125;
]

Troubleshooting

Cannot connect to WebSocket server
  • Ensure the flow is deployed
  • Check the path matches exactly (case-sensitive)
  • Verify firewall allows WebSocket connections on port 1880
  • For browsers, check CORS and mixed content (HTTP/HTTPS) issues
  • Try connecting with wscat: wscat -c ws://host:1880/path
Connection drops frequently
  • Enable heartbeat (hb property) to keep connection alive
  • Check for proxy or load balancer timeouts
  • Implement reconnection logic in your client code
  • Monitor network stability between client and server
Messages not received by specific client

To send to a specific client, preserve the _session object from the received message and pass it to websocket-out. Without _session, messages are broadcast to all connected clients.

Binary data handling

WebSocket supports binary data as ArrayBuffer or Buffer. The node will output binary data as a Node.js Buffer object. Use a function node to convert if needed:

// Buffer to string
msg.payload = msg.payload.toString('utf8');
// String to Buffer
msg.payload = Buffer.from(msg.payload);