I have a nodejs websocket server and need to send data from my serial port to the client every time it send data to me.
This is my ws on connection
wss.on('connection', ws => {
ws.on('message', message => {
console.log(`Received message => ${message}`)
})
ws.send('ho!')
})
This is my serial on Data
parser.on('data', (dados) => {
console.log(dados.toString('utf8'));
})
Basically, when the serial send me some data, i need to send it to the client.
Is there any way of making that trick? i thought that i could have some global variable and make it as a bridge between both actions.
ie: Whenever serial send me some data i put it on my variable and each 2 seconds my ws server sends whatever is in that variable to the client.
Inside your 'data' callback, instead of the line of console.log(dados.toString('utf8'));
you can put the below code:
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(dados.toString('utf8'));
}
});
the collection wss.clients
should contain only one ws client as i understand, based on your architecture.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.