I'm starting to use node js. So far everything was good. Untill today. I was playing with websockets, i'm able to establish a connection between the server and the browser. However, I cannot send messages from the server to the client using ws.send('something'); In almost every example I can find the methode is used, and in my situation it doest not seem to work. Can somebody explain me why?
const express = require('express');
const path = require('path');
const WebSocket = require('ws').Server;
const router = express.Router();
const SerialPort = require('serialport');
const barCode = new SerialPort('COM50', {
baudRate: 57600
});
// --------- SETUP WS ---------
var wsport = 8085;
var ws = new WebSocket({port: wsport});
ws.on('connection', function open() {
console.log('ws connection has been established.');
// ws.send('something'); this line is not working!
});
// !!-- BarCode:: Log errors to console when they occur.
barCode.on('error', function(err) {
console.log('Error: ', err.message);
});
barCode.on('data', function (data) {
console.log('Barcode received:', data);
ws.send('received barcode');
});
// --------- SETUP EXPRESS ---------
var app = express(); // Define the application object
var port = 4000; // Specify the port to listen to
router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/public/index.html'));
//__dirname : It will resolve to your project folder.
});
router.get('/offline',function(req,res){
res.sendFile(path.join(__dirname+'/public/offline.html'));
//__dirname : It will resolve to your project folder.
});
app.use(express.static('public'));
app.use('/', router);
app.listen(process.env.port || port);
console.log('Webserver running at port ' + port);
module.exports = app;
This is a very common mistake The thing here is the
var ws = new WebSocket({port: wsport});
ws.on('connection', function open() {
console.log('ws connection has been established.');
// ws.send('something'); this line is not working!
});
the variable created as an new Websocket, isn't valid inside the function
ws.on()
So as ws isn't a valid variable inside the function
ws.send() isn't a function, hence the error
Try calling another function inside ws.on(), that has the access to the variable ws where the object of the socket was created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With