Skip to content

Commit 4d52c24

Browse files
committed
examples: add a WebSocket example
There is nothing really to do in order to support events over websockets. Since a `CloudEvent` can easily be represented in full with JSON, it can be sent over a websocket as `event.toString()`. Fixes: #156
1 parent 0378f4c commit 4d52c24

File tree

4 files changed

+131
-0
lines changed

4 files changed

+131
-0
lines changed

examples/websocket/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# WebSocket Example
2+
3+
This example shows how simple it is to use CloudEvents over a websocket
4+
connection. The code here shows backend communication from two server
5+
side processes. However, this could be adapted to work within a browser.
6+
7+
## Running the Example
8+
9+
This simple project consists of a server and a client. The server receives
10+
`CloudEvents` from the client over a local websocket connection.
11+
12+
13+
To get started, first install dependencies.
14+
15+
```sh
16+
npm install
17+
```
18+
19+
### Server
20+
The server opens a websocket and waits for incoming connections. It expects that any
21+
messages it receives will be a CloudEvent. When received, it prints the string
22+
representation of the event, and then sends an acknowledgement message back over the
23+
websocket to the connected client. To start the server, run `node server.js`.
24+
25+
### Client
26+
Upon start, the client prompts a user for a zip code, then fetches the current weather
27+
for that zip code. It then prints the weather to the console, and constructs a `CloudEvent`
28+
with the body of the Weather API response as the event data. It sends this event to
29+
the server via its websocket connection as JSON. When it has received an ACK from the server
30+
it prints the acknowledge message, then asks again for a zip code.
31+
32+
To terminate the client or server, type CTL-C.

examples/websocket/client.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/* eslint-disable no-console */
2+
const readline = require("readline");
3+
const { CloudEvent } = require("cloudevents-sdk");
4+
5+
const WebSocket = require("ws");
6+
const got = require("got");
7+
8+
const api = "https://api.openweathermap.org/data/2.5/weather";
9+
const key = "506e9b3eef5b37d0bc745a5c9529788d";
10+
const ws = new WebSocket("ws://localhost:8080");
11+
12+
const rl = readline.createInterface({
13+
input: process.stdin,
14+
output: process.stdout
15+
});
16+
17+
rl.on("close", (_) => console.log("\n\nConnection closed! Press CTL-C to exit."));
18+
19+
function ask() {
20+
rl.question("Would you like to see the current weather? Provide a zip code: ", function (zip) {
21+
fetch(zip);
22+
});
23+
}
24+
25+
function fetch(zip) {
26+
const query = `${api}?zip=${zip}&appid=${key}&units=imperial`;
27+
got(query).then((response) => {
28+
print(response.body);
29+
deliver(response.body);
30+
}).catch((err) => {
31+
console.error(err.message);
32+
ask();
33+
});
34+
}
35+
36+
function print(data) {
37+
data = JSON.parse(data);
38+
console.log(`\nThe current weather for ${data.name}: ${data.weather[0].main}
39+
------------------------------------------
40+
With ${data.weather[0].description}, the temperature is ${Math.round(data.main.temp)}F
41+
and the wind is blowing at ${Math.round(data.wind.speed)}mph.`);
42+
}
43+
44+
function deliver(event) {
45+
console.log("\nSending weather data to remote server");
46+
ws.send(new CloudEvent({
47+
dataContentType: "application/json",
48+
type: "current.weather",
49+
source: api,
50+
data: event
51+
}).toString());
52+
}
53+
54+
ws.on("message", function incoming(data) {
55+
console.log(`Receieved response from server:\n${data}\n\n`);
56+
ask();
57+
});
58+
59+
ask();
60+
61+

examples/websocket/package.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "websocket-cloudevents",
3+
"version": "0.0.1",
4+
"description": "An example application that sends and receives CloudEvents over a websocket",
5+
"main": "server.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1",
8+
"start": "node server.js"
9+
},
10+
"keywords": [
11+
"cloudevents",
12+
"example",
13+
"websocket"
14+
],
15+
"author": "",
16+
"license": "ISC",
17+
"dependencies": {
18+
"cloudevents-sdk": "^2.0.2",
19+
"got": "^11.3.0",
20+
"ws": "^7.3.0"
21+
}
22+
}

examples/websocket/server.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/* eslint-disable no-console */
2+
const { CloudEvent } = require("cloudevents-sdk");
3+
const WebSocket = require("ws");
4+
const wss = new WebSocket.Server({ port: 8080 });
5+
6+
console.log("WebSocket server started. Waiting for events.");
7+
8+
wss.on("connection", function connection(ws) {
9+
console.log("Connection received");
10+
ws.on("message", function incoming(message) {
11+
const event = new CloudEvent(JSON.parse(message));
12+
console.log(`Message received: ${event.toString()}`);
13+
14+
ws.send(`Got ${event.type} from ${event.source} id ${event.id}`);
15+
});
16+
});

0 commit comments

Comments
 (0)