Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Echo microservoce using websocket #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions echo-websocket/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
9 changes: 9 additions & 0 deletions echo-websocket/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM node:alpine

ENV DEBUG=*

WORKDIR /src
COPY . .
RUN npm install

CMD npm start
61 changes: 61 additions & 0 deletions echo-websocket/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const ioFogClient = require('@iofog/nodejs-sdk')
const WebSocketServer = require('ws').Server

let port, wss
ioFogClient.init('iofog', 54321, null, main)

async function fetchConfig() {
const configRequest = () => new Promise((resolve, reject) => {
ioFogClient.getConfig({
'onBadRequest': reject,
'onError': reject,
'onNewConfig': resolve
})
})

try {
const config = await configRequest()
newPort = config.port || 8080
if (newPort !== port) {
if (wss) {
wss.clients.forEach(ws => ws.close())
}

port = newPort
wss = new WebSocketServer({ port })

console.log(`listening on port: ${port}`)

wss.on('connection', (ws) => {
console.log('new client connected!')
ws.send('connected!')
ws.on('message', (message) => {
console.log(message)
ws.send('echo: ' + message)
})
})

wss.on('close', () => {
console.log('disconnected');
})
}
} catch (e) {
console.error(e)
process.exit(1)
}

}

async function main() {
await fetchConfig()

ioFogClient.wsControlConnection({
'onNewConfigSignal': async () => {
await fetchConfig()
},
'onError': (error) => {
console.error('There was an error with Control WebSocket connection to ioFog: ', error)
process.exit(1)
}
})
}
15 changes: 15 additions & 0 deletions echo-websocket/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "echo-websocket",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"@iofog/nodejs-sdk": "1.3.0",
"ws": "7.2.1"
}
}