📝Examples
Discover code examples in various languages for establishing connections to our server and efficiently listening for real-time data updates. Choose from Python, Go, JavaScript, and more. Integrate sea
const WebSocket = require('ws');
const socketUrl = "wss://ws.flow.simplemonitors.com/ws";
let ws;
let reconnectInterval;
let stopReconnect = false; // Flag to track reconnection attempts
const authenticateConnection = () => {
const authMessage = {
type: 'auth',
data: {
app: "<app name>",
key: "<user UUID>",
}
};
ws.send(JSON.stringify(authMessage));
}
const onOpen = () => {
console.log('Connected to Flow API');
authenticateConnection();
clearInterval(reconnectInterval);
}
const onMessage = (message) => {
const response = JSON.parse(message);
switch (response.type) {
case 'auth_success':
console.log('Successfully authenticated and connected to Flow API.');
break;
case 'auth_failed':
console.log('Authentication failed. Stopping reconnection attempts.');
stopReconnect = true;
ws.close();
break;
case 'data':
const feedData = response.data;
const { platform, name, locale, siteOrigin, status, time } = feedData;
console.log(`Feed data: Platform=${platform}, Name=${name}, Locale=${locale}, Domain=${siteOrigin}, Status=${status}, Time=${time}`);
break;
default:
console.log(`Unknown message type '${response.type}': ${response.message}`);
}
}
const onClose = () => {
console.log('Disconnected from Flow API');
if (!stopReconnect) {
reconnect();
}
}
const connectToServer = () => {
ws = new WebSocket(socketUrl);
ws.on('open', onOpen);
ws.on('message', onMessage);
ws.on('close', onClose);
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
}
const reconnect = () => {
if (stopReconnect) {
return; // Stop reconnection attempts if flag is set
}
clearInterval(reconnectInterval);
console.log('Reconnecting in 5 seconds...');
reconnectInterval = setInterval(() => {
console.log('Attempting to reconnect...');
connectToServer();
}, 5000);
}
connectToServer();package main
import (
"encoding/json"
"log"
"time"
"github.com/gorilla/websocket"
)
const (
socketURL = "wss://ws.flow.simplemonitors.com/ws"
)
var (
ws *websocket.Conn
reconnectTimer *time.Timer
stopReconnect = false
authenticated = false
)
type authMessage struct {
Type string `json:"type"`
Data struct {
App string `json:"app"`
Key string `json:"key"`
} `json:"data"`
}
type feedMessage struct {
Type string `json:"type"`
Data feedData `json:"data"`
}
type responseMessage struct {
Type string `json:"type"`
Message string `json:"message"`
Data feedData `json:"data"`
}
type feedData struct {
Platform string `json:"platform"`
Name string `json:"name"`
Locale string `json:"locale"`
Domain string `json:"siteOrigin"`
Status string `json:"status"`
Time int `json:"time"`
Products []Product `json:"products"`
}
type Product struct {
ID string `json:"id"`
Title string `json:"title"`
Price float64 `json:"price"`
}
func authenticateConnection() {
authMsg := authMessage{
Type: "auth",
Data: struct {
App string `json:"app"`
Key string `json:"key"`
}{
App: "<app name>",
Key: "<user UUID>",
},
}
if ws != nil {
err := ws.WriteJSON(authMsg)
if err != nil {
log.Println("Failed to send authentication message:", err)
}
}
}
func onOpen() {
log.Println("Connected to Flow API")
authenticateConnection()
if reconnectTimer != nil {
reconnectTimer.Stop()
}
}
func onMessage(message []byte) {
var response responseMessage
err := json.Unmarshal(message, &response)
if err != nil {
log.Println("Failed to parse message:", err)
return
}
switch response.Type {
case "auth_success":
log.Println("Successfully authenticated and connected to Flow API.")
case "auth_failed":
var authFailed struct {
Type string `json:"type"`
Message string `json:"message"`
}
err := json.Unmarshal([]byte(response.Message), &authFailed)
if err != nil {
log.Println("Failed to parse auth_failed message:", err)
return
}
log.Println("Authentication failed:", authFailed.Message)
stopReconnect = true
if ws != nil {
ws.Close()
}
case "data":
log.Printf("Feed data: Platform=%s, Name=%s, Locale=%s, siteOrigin=%s, Status=%s, Time=%d\n",
response.Data.Platform, response.Data.Name, response.Data.Locale, response.Data.Domain, response.Data.Status, response.Data.Time)
default:
log.Printf("Unknown message type: %s\n", response.Type)
}
}
func onClose() {
log.Println("Disconnected from Flow API")
if !stopReconnect {
reconnect()
}
}
func connectToServer() {
var err error
ws, _, err = websocket.DefaultDialer.Dial(socketURL, nil)
if err != nil {
log.Println("Failed to connect to server:", err)
reconnect()
return
}
ws.SetCloseHandler(func(code int, text string) error {
onClose()
return nil
})
log.Println
oimport json
import logging
import time
import websocket
socket_url = "wss://ws.flow.simplemonitors.com/ws"
ws = None
reconnect_timer = None
stop_reconnect = False
authenticated = False
def authenticate_connection():
auth_msg = {
"type": "auth",
"data": {
"app": "<app name>",
"key": "<user UUID>"
}
}
if ws is not None:
ws.send(json.dumps(auth_msg))
def on_open(ws):
logging.info("Connected to Flow API")
authenticate_connection()
if reconnect_timer is not None:
reconnect_timer.cancel()
def on_message(ws, message):
response = json.loads(message)
if response["type"] == "auth_success":
logging.info("Successfully authenticated and connected to Flow API.")
elif response["type"] == "auth_failed":
auth_failed = json.loads(response["message"])
logging.error("Authentication failed: %s", auth_failed["message"])
stop_reconnect = True
if ws is not None:
ws.close()
elif response["type"] == "data":
data = response["data"]
logging.info("Feed data: Platform=%s, Name=%s, Locale=%s, siteOrigin=%s, Status=%s, Time=%d",
data["platform"], data["name"], data["locale"], data["siteOrigin"], data["status"], data["time"])
else:
logging.warning("Unknown message type: %s", response["type"])
def on_close(ws):
logging.info("Disconnected from Flow API")
if not stop_reconnect:
reconnect()
def connect_to_server():
global ws
ws = websocket.WebSocketApp(socket_url,
on_open=on_open,
on_message=on_message,
on_close=on_close)
ws.run_forever()
def reconnect():
global stop_reconnect, reconnect_timer
if stop_reconnect:
return
logging.info("Reconnecting in 5 seconds...")
reconnect_timer
Last updated