ReferenceError: Socket is not defined .....while creating a NODE SERVER using Socket.io

561 Views Asked by At

I was creating a Chat Application using Node JS where i have been using Socket.Io library to build a two way connection between the client and the web server.

Here is my code (Creating Node Server):

// Node Server that will handle Socket io connections

const io = require('socket.io')(3000)            // Requiring the socket io Library

const users = {};

io.on("connections", (socket) => {
    socket.on("new-user-joined", (name) => {
        users[socket.id] = name;    
        socket.broadcast.emit("user-joined", name)
    });
});

socket.on('send', message =>{
    socket.broadcast.emit('recieve', {message: message, name: users[socket.id]});
});

My node server stop and display this error :

Problem:

    PS C:\Users\SANKET PRAKHER\Desktop\complete web development bootcamp\Chat Application\Node Server> nodemon .\index.js
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node .\index.js`
C:\Users\SANKET PRAKHER\Desktop\complete web development bootcamp\Chat Application\Node Server\index.js:14
socket.on('send', message =>{
^

ReferenceError: socket is not defined
    at Object.<anonymous> (C:\Users\SANKET PRAKHER\Desktop\complete web development bootcamp\Chat Application\Node Server\index.js:14:1)
    at Module._compile (internal/modules/cjs/loader.js:1015:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
    at Module.load (internal/modules/cjs/loader.js:879:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
1

There are 1 best solutions below

2
sçuçu On

Your reference to variable socket where you wrote socket.on('send', ... is simply out of scope where the socket itself is a defined variable. This variable only defined in the function that you give as second argument to the io.on call and should be referenced there normally. And that function takes it as an argument named socket by the way.

So you should carry your socket.on code block inside that function:

io.on("connections", (socket) => {
    socket.on("new-user-joined", (name) => {
        users[socket.id] = name;    
        socket.broadcast.emit("user-joined", name)
    });
    socket.on('send', message => {
        socket.broadcast.emit('recieve', {message: message, name: users[socket.id]});
    });
});

just like you do for the socket.on('new-user-joined', ...)