Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages to all browsers with socket io

I am messing around with socket.io and node.js, and was wondering how to accomplish the following: I have a simple form that sends a text string to the server, and the server sends it back, and it gets appended to a div. what I would like to do is have that div update for all users in all browsers, currently it only updates the one that the message was sent from.

code from app.js (node.js server) :

io.sockets.on('connection', function(socket) {
    socket.on('send_message', function(data) {
    data.message = data.message + ' yo<br/>';
    socket.emit('get_message',data);
    });
}); 

code on client-side:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
    $(document).ready(function() {
    var socket = io.connect('http://localhost:3000');

    $('#sender').live('click',function() {
            var user_message = $('#message_box').val()
            socket.emit('send_message',{message: user_message});
    });

    socket.on('get_message', function(data) {
        $('#data').append(data.message);
        });
    });
</script>

and the html:

<div id='data'></div>
<input type='text' id='message_box' placeholder='send message'>
<button id='sender'>Send Message</button>

what should I be doing to send messages to multiple browsers?

like image 532
GSto Avatar asked Sep 20 '11 19:09

GSto


1 Answers

Change

socket.emit('get_message',data);

To

socket.broadcast.emit('get_message',data);

To broadcast it to all connected users, except to the socket where you are calling the broadcast on.

If you also want to include that socket you can do

io.sockets.emit('get_message', data);
like image 111
3rdEden Avatar answered Oct 12 '22 13:10

3rdEden