Raggaer
Raggaer

Reputation: 3318

Socket.io not listening

im using this simple code

Client.html

http://pastebin.com/c1C2F9MQ

Server.js

http://pastebin.com/Cqjhjfwm

Everything working fine till the last step of my client code

socket.on('add', function(data) {

    socket.broadcast.emit('AAA');

});

It seems that the socket add never comes but on my server I have

socket.on('Text', function(data) {

socket.emit('add', data);

});

And I tested if socket text was coming and it does, I cant find the problem Thanks

Upvotes: 2

Views: 2875

Answers (2)

user568109
user568109

Reputation: 47993

socket.broadcast.emit sends message to all sockets connected to server except the concerned socket. So most likely add does come to server but it broadcasts AAA which your client cannot get. Use io.sockets.emit to send to all connected sockets. Change this

socket.broadcast.emit('AAA');

to

io.sockets.emit('AAA');

Update

I too overlooked that you are calling socket.broadcast.emit from client not from server. It would have shown error on browser console, since broadcast is absent on client.

Upvotes: 1

Ed_
Ed_

Reputation: 19098

Currently your on('add') code on the client side is within the on('connect') event which is not correct...

You need to take it ouside there, so it becomes:

socket.on('connect', function () {
    $('#button').click(function() {  
        var addtext = $('#text').val();
        socket.emit('Text', addtext);
    });
});

socket.on('add', function(data) {  
    socket.emit('AAA');  
});

EDIT: I also just noticed you had socket.broadcast.emit() in your client side code. As far as I know there's no concept of broadcasting from the client. If you want to broadcast something then the client should send it to the server then the server broadcasts to the other clients.

Upvotes: 0

Related Questions