Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 970
Lalit Kushwah Avatar asked Jan 28 '26 22:01

Lalit Kushwah


1 Answers

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);
});
like image 143
Krzysztof Sztompka Avatar answered Jan 31 '26 14:01

Krzysztof Sztompka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!