3

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;

1
  • 1
    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. Commented Jan 24, 2019 at 14:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
var ws_server = new WebSocket({ port: wsport });
ws_server.on('connection', (ws_socket) => {
    ws_socket.send('something'); 
});

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.