Create Websocket server locally
Install the ws package
1npm i ws
Create a server.js file and add the following contents
1import { WebSocketServer } from "ws";
2
3const wss = new WebSocketServer({ port: 8099 })
4wss.on('connection', client => {
5 console.log(`Connected New Client : Total size ${wss.clients.size}`);
6 wss.clients.forEach(c => {
7 c.send(`{"connected_devices": ${wss.clients.size}}`)
8 })
9
10 client.on('message', (data, isBinary) => {
11 [...wss.clients]
12 .filter(c => c != client)
13 .forEach(c => {
14 c.send(`{"data": "${data}"}`)
15 })
16 })
17
18 client.on('close', () => {
19 console.log(`Devices Disconnected. Total size ${wss.clients.size}`);
20 [...wss.clients]
21 .filter(c => c != client)
22 .forEach(c => {
23 c.send(`{"connected_devices": ${wss.clients.size}}`)
24 })
25 })
26})
Run server locally
1node server.js
For containerized app
Create a dockerignore file
1node_modules
2npm-debug.log
Create a docker file Dockerfile
1FROM node:16-alpine
2WORKDIR /usr/src/app
3COPY package*.json ./
4RUN npm ci --only=production
5COPY . .
6EXPOSE 8099
7CMD [ "node", "server.js" ]
Build image
1docker build -t datavedam-websocket:latest .
Run container locally
1docker run -p 8099:8099 datavedam-websocket:latest
Deploy a container to Cloud run
To deploy container to cloud run, Follow the docs