Code Samples
Subscribe to all stream posts you follow
import * as ws from 'ws';
const WS_API_ENDPOINT = 'wss://api.synoptic.com/v1/ws';
const API_KEY = 'YOUR_API_KEY';
let client: ws.WebSocket | null = null;
const RECONNECT_DELAY_MS = 5000;
function connect() {
client = new ws.WebSocket(
`${WS_API_ENDPOINT}/on-stream-post?apiKey=${API_KEY}`,
);
client.onopen = () => {
console.log('Connected to the server');
// Connection established
};
client.onmessage = (event) => {
console.log('Received message:', event.data);
// TODO: Handle incoming messages
};
client.onerror = (error) => {
console.error('WebSocket error:', error);
// Reconnect on error
cleanupAndReconnect();
};
client.onclose = () => {
console.log('WebSocket connection closed');
// Reconnect on close
cleanupAndReconnect();
};
}
function cleanupAndReconnect() {
if (client) {
client.removeAllListeners();
client = null;
}
setTimeout(connect, RECONNECT_DELAY_MS);
}
connect();import websocket
import time
WS_API_ENDPOINT = 'wss://api.synoptic.com/v1/ws'
API_KEY = 'YOUR_API_KEY'
RECONNECT_DELAY_SEC = 5
def run_ws():
ws_url = f"{WS_API_ENDPOINT}/on-stream-post?apiKey={API_KEY}"
while True:
try:
ws = websocket.create_connection(ws_url)
print('Connected to the server')
while True:
try:
message = ws.recv()
if message is None:
print('WebSocket connection closed by server')
break
print('Received message:', message)
except websocket.WebSocketConnectionClosedException:
print('WebSocket connection closed')
break
except Exception as e:
print('WebSocket error:', e)
break
except Exception as e:
print('WebSocket connection failed:', e)
finally:
try:
ws.close()
except Exception:
pass
print(f"Reconnecting in {RECONNECT_DELAY_SEC} seconds...")
time.sleep(RECONNECT_DELAY_SEC)
if __name__ == "__main__":
run_ws()
Last updated