开发者

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://l开发者_开发问答ocalhost: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?


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜