fvempy
fvempy

Reputation: 21

socket.on() not receiving data

I am having a problem with getting socket.on to work

$('#showmsg').click(function() {
var socket = io.connect('http://localhost:3000');
var msgText = $('#msgtext');
socket.emit('show msg', msgText.val());
});

That code works, as shown by using

io.sockets.on('connection', function(socket) {
    socket.on('show msg', function(data) {
        console.log(data);
    });
});

in server.js, my main app file, however in another file, when I use the code

    $(document).ready(function (){
        var socket = io.connect();
        socket.on('show msg', function(data) {
            $('#container').hide();
        });
    });

Nothing happens. Does anyone know how I can get this code to work?

Upvotes: 0

Views: 2222

Answers (3)

priyabagus
priyabagus

Reputation: 2878

Nothing happens because you don't emit anything.

$(document).ready(function (){
  var socket = io.connect('http://localhost:3000');
  socket.on('show msg', function(data) {
    $('#container').hide();
  });
  socket.emit('show msg', 'right now I am emitting data');
});

Upvotes: 1

Alex J
Alex J

Reputation: 1019

I think what's happening is that in your document.ready function, you are trying to call io.connect() but you are then calling the show message before your socket has connected. Try doing it like this

socket.on('connect', function (){
   socket.on('show msg', function(data) {
        $('#container').hide();
    });
});

Upvotes: 1

jfriend00
jfriend00

Reputation: 708016

When you connect in the client, you have to wait for the connect message before you can send data with .emit(). As you have it now, you are trying to send the data before the connection has finished so the data is lost.

See the client-side example here: http://socket.io/docs/#sending-and-getting-data-(acknowledgements)

Upvotes: 1

Related Questions