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;
In almost every example I can find the methode is used,not from the docs it's not. npmjs.com/package/ws#sending-and-receiving-text-data IOW: try ->ws.on('connection', function open(ws) {Also might be worth changing the var called ws in your case to wss to match docs's and save confusion.