In my setup for an expressJS server with a socket.IO connection, the application continuously reads sensor data every 10 seconds and pushes it to all clients without any issues.
However, there is also a functionality where a client can call /set-status
with parameters to update some status data. In this scenario, simply using a request/response approach won't work as the updated status data needs to be sent to all clients simultaneously.
So, what steps should I take to trigger the socketIO connection after the /set-status
endpoint has been invoked?
const express = require('express')
const http = require('http')
const socketIo = require('socket.io')
const app = express()
const server = http.createServer(app)
const io = socketIo(server)
io.on('connection', socket => {
getStatus(socket)
getData(socket)
setInterval(
() => getData(socket),
10000
)
})
app.get('/set-status', (req, res) => {
// Change some data and broadcast new data to all clients
// How do I access the socket object?
res.send(200, 'new-data')
})
const getStatus = async socket => {
const res = { initial: 'data' }
socket.emit('exampleStatus', res)
}
const getData = async socket => {
// read some sensor data which updates every 10 seconds
// this part works fine
const res = { some: 'sensor data' }
socket.emit('sensorData', res)
}
server.listen(port, () => {
if (process.env.NODE_ENV !== 'production') {
console.log(`Listening on port ${port}`)
}
})