Improve websocket tutorial:

- Use correct Testnet faucet address
- Comment that API requests have to wait for the socket to be connected
- Add example file with combined examples
This commit is contained in:
mDuo13
2021-03-08 18:33:02 -08:00
parent 33f6fbf7b2
commit 38724a4b92
3 changed files with 112 additions and 4 deletions

View File

@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="application/javascript" src="monitor-payments.js"></script>
</head>
<body>
<p>(Open your browser's console with F12 and check the logs.)</p>
</body>
</html>

View File

@@ -0,0 +1,98 @@
const socket = new WebSocket('wss://s.altnet.rippletest.net:51233')
socket.addEventListener('message', (event) => {
console.log('Got message from server:', event.data)
})
socket.addEventListener('close', (event) => {
// Use this event to detect when you have become disconnected
// and respond appropriately.
console.log('Disconnected...')
})
const AWAITING = {}
const handleResponse = function(data) {
if (!data.hasOwnProperty("id")) {
console.error("Got response event without ID:", data)
return
}
if (AWAITING.hasOwnProperty(data.id)) {
AWAITING[data.id].resolve(data)
} else {
console.warn("Response to un-awaited request w/ ID " + data.id)
}
}
let autoid_n = 0
function api_request(options) {
if (socket.readyState === 0) {
console.error("Socket is not connected yet")
return
}
if (!options.hasOwnProperty("id")) {
options.id = "autoid_" + (autoid_n++)
}
let resolveHolder;
AWAITING[options.id] = new Promise((resolve, reject) => {
// Save the resolve func to be called by the handleResponse function later
resolveHolder = resolve
try {
// Use the socket opened in the previous example...
socket.send(JSON.stringify(options))
} catch(error) {
reject(error)
}
})
AWAITING[options.id].resolve = resolveHolder;
return AWAITING[options.id]
}
const WS_HANDLERS = {
"response": handleResponse
// Fill this out with your handlers in the following format:
// "type": function(event) { /* handle event of this type */ }
}
socket.addEventListener('message', (event) => {
const parsed_data = JSON.parse(event.data)
if (WS_HANDLERS.hasOwnProperty(parsed_data.type)) {
// Call the mapped handler
WS_HANDLERS[parsed_data.type](parsed_data)
} else {
console.log("Unhandled message from server", event)
}
})
// Demonstrate api_request functionality
async function pingpong() {
console.log("Ping...")
const response = await api_request({command: "ping"})
console.log("Pong!", response)
}
async function do_subscribe() {
const sub_response = await api_request({
command:"subscribe",
accounts: ["rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"]
})
if (sub_response.status === "success") {
console.log("Successfully subscribed!")
} else {
console.error("Error subscribing: ", sub_response)
}
}
const log_tx = function(tx) {
console.log(tx.transaction.TransactionType + " transaction sent by " +
tx.transaction.Account +
"\n Result: " + tx.meta.TransactionResult +
" in ledger " + tx.ledger_index +
"\n Validated? " + tx.validated)
}
WS_HANDLERS["transaction"] = log_tx
socket.addEventListener('open', (event) => {
// This callback runs when the connection is open
console.log("Connected!")
pingpong()
do_subscribe()
})

View File

@@ -142,7 +142,7 @@ const handleResponse = function(data) {
if (AWAITING.hasOwnProperty(data.id)) {
AWAITING[data.id].resolve(data)
} else {
console.error("Response to un-awaited request w/ ID " + data.id)
console.warn("Response to un-awaited request w/ ID " + data.id)
}
}
@@ -188,7 +188,7 @@ async function pingpong() {
const response = await api_request({command: "ping"})
console.log("Pong!", response)
}
pingpong()
// Add pingpong() to the 'open' listener for socket
```
{{ start_step("Dispatch Messages") }}
@@ -272,7 +272,7 @@ The following code sample subscribes to the Test Net Faucet's sending address. I
async function do_subscribe() {
const sub_response = await api_request({
command:"subscribe",
accounts: ["rUCzEr6jrEyMpjhs4wSdQdz4g8Y382NxfM"]
accounts: ["rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"]
})
if (sub_response.status === "success") {
console.log("Successfully subscribed!")
@@ -280,7 +280,7 @@ async function do_subscribe() {
console.error("Error subscribing: ", sub_response)
}
}
do_subscribe()
// Add do_subscribe() to the 'open' listener for socket
const log_tx = function(tx) {
console.log(tx.transaction.TransactionType + " transaction sent by " +