Escucha desde Node.js
Un pequeño script de Node.js que recibe los mensajes y se vuelve a conectar cuando se corta la conexión.
En esta página
Node.js 22 y posteriores tienen WebSocket integrado, así que este script no necesita paquetes.
El script
Guárdalo como listen.js, con tu dirección y tu token:
const URL = 'wss://sync.example.com/?token=YOUR_TOKEN&app=Warehouse';
function connect() {
const ws = new WebSocket(URL);
ws.onmessage = function(e) {
const msg = JSON.parse(e.data);
if (msg.type === 'init') {
console.log('Connected to', msg.name);
return;
}
console.log(msg.channel, msg.method, JSON.stringify(msg.body));
};
ws.onclose = function() {
console.log('Disconnected, trying again in 3 seconds');
setTimeout(connect, 3000);
};
}
connect();Ejecútalo
node listen.jsEnvía un pedido y luego bórralo:
curl -X POST -H "Content-Type: application/json" -d '{"id":1002,"status":"paid"}' "https://sync.example.com/sync/orders/"
curl -X DELETE "https://sync.example.com/sync/orders/?id=1002"El script muestra esto, también si OpenSync se reinicia entretanto:
Connected to Demo sync
orders POST {"id":1002,"status":"paid"}
Disconnected, trying again in 3 seconds
Connected to Demo sync
orders DELETE ""Los mensajes enviados mientras el script estaba desconectado no se entregan después.
Envía desde el mismo script
Para enviar un mensaje a los demás clientes, llama a send en la conexión abierta:
ws.send(JSON.stringify({ type: 'notify', channel: 'chat', body: { text: 'Hello' } }));Consulta WebSocket.