ReferenceError: client is not defined Socket.io

503 views Asked by At

How to solve this? I don't get it,,please help, thanks. And this is the error message when I run node server.js:

client.on('getRelay', function (state) { ReferenceError: client is not defined

var express = require ('express');
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = 3000;

let bodyRelay = {
    relayId: 'RELAY-123',
    state: 1
}

app.use(express.static(__dirname + '/node_modules'));
app.get('/', function(req, res, next) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(client) {
    console.log('a user has connected');

});

io.sockets.emit('setRelay', bodyRelay);
client.on('getRelay', function (state) {
    bodyRelay = state;
    console.log('id: ' + client.id + 'bodyRelay: ' + JSON.stringify(bodyRelay));
    // io.sockets.emit('setRelay', bodyRelay);
});

client.on('disconnect', function() {
    console.log('a user has disconnected');
});

server.listen(port, () => {
    console.log('Server is running on port: ' + port)
});

1

There are 1 answers

0
jfriend00 On

The blocks of code that reference client, must be inside this callback:

io.on('connection', function(client) {
    console.log('a user has connected');

});

because that is where client is defined. Like this:

io.on('connection', function(client) {
    console.log('a user has connected');

    client.on('getRelay', function (state) {
        bodyRelay = state;
        console.log('id: ' + client.id + 'bodyRelay: ' + JSON.stringify(bodyRelay));
        // io.sockets.emit('setRelay', bodyRelay);
    });

    client.on('disconnect', function() {
        console.log('a user has disconnected');
    });
});

A few other notes on your code.

The location you have this:

io.sockets.emit('setRelay', bodyRelay);

does not make any sense because you're calling it when you initialize the module which will NEVER have any connected socket.io clients so it will not do anything useful.

And, the way you are using the bodyRelay variable seems like a possible design error. You've made it a module-level variable which means it is shared among all request handlers for all connections. Unless this is intended to be something that all clients can change and all clients access the exact same set of data, then it perhaps needs a different design. I don't know what you're really trying to do with it to know what design to suggest.