|
1 | 1 | const express = require("express")
|
2 | 2 | const http = require("http")
|
3 | 3 | const WebSocket = require("ws")
|
| 4 | + |
| 5 | +// Broadcaster is a class that emit event when a new datapoint arrive |
| 6 | +// This is just an emulation of real life situation where datapoint came in randomly |
4 | 7 | const Broadcaster = require ("./Broadcaster")
|
5 | 8 |
|
6 | 9 | const app = express()
|
7 | 10 |
|
| 11 | +// Create own HTTP server instead of using app.listen() in order to share the same port with WS |
8 | 12 | const httpServer = http.createServer(app)
|
9 | 13 |
|
| 14 | +// Initating all middleware for express |
10 | 15 | app
|
11 | 16 | .set("views", `${process.cwd()}/src/server/views`)
|
12 | 17 | .set("view engine", "pug")
|
13 | 18 | .use(express.static(`${process.cwd()}/src/client`))
|
14 | 19 |
|
| 20 | +// Render index.pug from views for root URL |
15 | 21 | app
|
16 | 22 | .get("/", (req, res) => {
|
17 | 23 | res.render("index")
|
18 | 24 | })
|
19 | 25 |
|
20 |
| - |
| 26 | +// Initiate websocket server with the same server as express |
21 | 27 | const wss = new WebSocket.Server({ server: httpServer })
|
22 | 28 |
|
| 29 | +// Create new Broadcaster |
| 30 | +// Maybe you can add multiple broadcaster for multiple bus using the same data to make it a little interesting |
23 | 31 | const broadcaster = new Broadcaster()
|
24 | 32 |
|
25 | 33 | broadcaster.start()
|
26 | 34 | broadcaster.on("data", (data) => {
|
| 35 | + // Send data to all connected clients on websocket |
27 | 36 | wss.clients.forEach((socket) => {
|
28 | 37 | socket.send(JSON.stringify(data))
|
29 | 38 | })
|
30 | 39 | })
|
31 | 40 |
|
32 |
| - |
| 41 | +// Start listening on port 3000 for both express app and WS server |
33 | 42 | httpServer.listen(3000, () => {
|
34 | 43 | console.log("HTTP server listening on port 3000")
|
35 | 44 | })
|
|
0 commit comments