0

Client:

var socket = io.connect();
socket.on('some stuff', function(){
console.log("Please please work.");
});

Server:

var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket){

console.log("Yay, tab opened!");



 socket.on('disconnect', function(){
     console.log("Aww, tab closed. ");
 });

 socket.on('some stuff', function(){
     console.log("Did it work? Idk.");
 });


});

App is just a server which is irrelevant. When I run it, the only part that works is the tab open tab closed part. When I open up localhost and go on there, it says "yay tab opened" in the windows console. (And when I open more tabs, it says that message for every tab I open). When I close tabs, it says the aww tab closed message for every tab I close.

BUT when I am trying to add my own function, it doesn't care to log in. I realize that I'm not doing anything with that function yet, but I will need it later on. So I want to know why it's not logging it. The disconnect works, but the "some stuff" doesn't work. Why not?

Hellothere
  • 233
  • 3
  • 15
  • Possible dup of: http://stackoverflow.com/questions/29108594/node-js-socket-io-client-is-not-connecting-to-socket-io-server/29113237#29113237 – jfriend00 Mar 21 '15 at 04:23

1 Answers1

0

If you want your client side to send a message back you have to call emit:

// client
socket.emit('some stuff', {my:data});

// server
socket.on("connection", function() {
    ...

    socket.on("some stuff",function(data){
        console.log(data)
    );
});

The process can be reversed of course so you can send data from server to client with your own function

Ibu
  • 42,752
  • 13
  • 76
  • 103
  • Thanks! Also, if I am trying to pass that data into another function inside that socket.on function, how do I do that? I am trying to do db.serialize(function(data)//do some db stuff and then {console.log(data);}), but it says that data is undefined. Even though before I passed it into that function, it logged data just fine. And in the database it stores itself as null. – Hellothere Mar 21 '15 at 05:31
  • I'm not familiar with the db.serialize function. But do note that all your variables are called data. maybe there is name collision? – Ibu Mar 21 '15 at 05:40