Lalit Kushwah
Lalit Kushwah

Reputation: 4049

Cannot read property 'on' of undefined in socket.io

i am getting this error(undefined 'on'). Here is my Server code

        var app = require('express')();
        var http = require('http').Server(app);
        var io = require('socket.io')(http);

        app.get('/', function(req, res){
          res.send('Hello');
        });

        io.on('connection', function(socket){
          console.log('a user connected');
            io.emit('EPSON', {'name':'Lalit'});
            console.log("Event Emitted successfully");

        });


        http.listen(3000, function(){
          console.log('listening on *:3000');
        });

    Here is my client code:

    var io = require('socket.io-client');
    //var socket = io.connect('http://printserverproject-happylaundry.rhcloud.com:8000');
    var socket = io.connect('http://172.20.20.240:3000');

    socket.on('connect', function(sock) 
    {
       console.log('Connected!');
       sock.on('EPSON',function(data)
       {
        console.log(data);
       });

    });

When i am running both the code connection is done but the at the client side the error occurs.

Upvotes: 3

Views: 13332

Answers (1)

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

You have to change your client code :

sock.on('EPSON',function(data)

to

socket.on('EPSON',function(data)

This is because you assume that client listener for connect return socket:

socket.on('connect', function(sock)

but it doesn't return anything. You have to bind event listeners to socket. This is different then in server side, because in frontend you have one client socket, but in backed you have all clients sockets.

Im also not convinced how you create socket in client, maybe it is also good solution, but I know and use:

var io = require('socket.io-client');
var socket = io('http://172.20.20.240:3000');

maybe this is because you use old version?

In summary your client code can look like :

var io = require('socket.io-client');
var socket = io('http://172.20.20.240:3000');
socket.on('connect', function(sock) 
{
   console.log('Connected!');
});
socket.on('EPSON',function(data)
{
  console.log(data);
});

Upvotes: 1

Related Questions