简体   繁体   中英

Can't send message to all sockets (socket.io)

Heya I'm trying to build a small chat client to learn how websockets work in order to make a game in canvas. It works great with sending sockets but they are only sending it to the the one who wrote it.

I guess I've missed something small, but I can't understand why it won't work.

Server side code

var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.listen(3000);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection', function (socket) {
  socket.on('user-message', function (data) {
    console.log(data);
    sendMessage(data.message);
  });
});

var sendMessage = function(message) {
      io.sockets.emit('server-message', {message: message});
}

Client side code

        <script src="/socket.io/socket.io.js"></script>
        <script>
            var socket = io.connect('http://localhost');

            socket.on('server-message', function (data) {
                var history = $('#chatbox').val();

                $('#chatbox').val(history + "\n" + data.message)
            });


            $("#write").keyup(function(event){
                if(event.keyCode == 13){
                    socket.emit('user-message', {message: $(this).val()});
                    $(this).val('');
                }
            });
        </script>

You can use socket.broadcast.emit to send a message to all other sockets.

io.sockets.on('connection', function (socket) {
    socket.on('user-message', function (data) {
        console.log(data);
        sendMessage.call(socket, data.message);
    });
});
var sendMessage = function(message) {
      this.emit('server-message', {message: message});
      this.broadcast.emit('server-message', {message: message});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM