Skip to content

Instantly share code, notes, and snippets.

@shannonwells
Last active August 17, 2020 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shannonwells/570fa94fddab6e58affbf981d8edf1d5 to your computer and use it in GitHub Desktop.
Save shannonwells/570fa94fddab6e58affbf981d8edf1d5 to your computer and use it in GitHub Desktop.
Toy websocket client
const express = require('express');
const app = express();
const WebSocket = require("ws");
app.get('/', function (req, res) {
res.send('This is not really a web page.');
});
const port = 3997
const wsPort = 3998
app.listen(3997, function () {
console.log(`Example app listening on port ${port}!`);
let receivedEvents = 0;
const ids = [
"0x60674ffbef620598f735d6c9c120b422c48830a6",
"0x60674ffbef620598f735d6c9c120b422c48830a6",
"0x4c9178b95977de41690c6067a771388147b3a70b"
]
try {
const ws = new WebSocket(`ws://localhost:${wsPort}`)
.on("message", (msg) => {
const decoded = JSON.parse(msg);
switch (decoded.type) {
case "connected":
console.log("connected")
ws.send(JSON.stringify({ ids: ids }));
break;
case "subscribed":
console.log("Subscribed")
break;
case "data":
case "changed":
receivedEvents++;
console.log("new event: ", decoded);
break;
default:
ws.close();
}
})
.on("ping", () => {
console.log("got ping");
})
.on("close", () => {
console.log("woohoo!");
});
} catch (e) {
console.log("error: ", e)
}
});
{
"name": "untitled",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dev-dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"ws": "^7.3.1"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"ws": "^7.3.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment