【问题标题】:Broadcast updated data to all clients connected to nodejs server over socket.io通过 socket.io 向所有连接到 nodejs 服务器的客户端广播更新的数据
【发布时间】:2013-05-04 05:18:32
【问题描述】:

我正在编写一个应用程序,当客户端通过 ajax 请求连接到本地套接字服务器并更新系统时,它需要能够更新所有连接的客户端。处理请求很好,但是将响应从本地套接字服务器发送到 socket.io 以广播给所有人是我遇到问题的地方。我确定我在这里查看的内容很简单,但这对我来说很新,所以我遇到了问题,特别是异步编程思维方式。以下是我正在努力完成的工作以及我在哪里步履蹒跚的简短版本。

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

app.get("/execute", function (req, res) {
    // connect to local socket server
    var localSock = net.createConnection("10000","127.0.0.1");
    localSock.setEncoding('utf8');

    localSock.on('data', function(data) {
        // send returned results from local socket server to all clients
        do stuff here to data ...
        send data to all connected clients view socketio socket...
        var dataToSend = data;
        localSock.end();

    }).on('connect', function(data) {
        // send GET data to local socket server to execute
        var command = req.query["command"];
        localSock.write(command);   
});

app.get (..., function() {});

app.get (..., function() {});

server.listen('3000');

io.on('connection', function(client) {
    client.broadcast.send(dataToSend);
});

【问题讨论】:

  • 在你对套接字服务器执行.write() 之后尝试调用io.emit('commandExecuted',dataToSend),它应该向连接到socket.io 服务器的所有客户端发出一个事件。sn-p 看起来有点不完整。 .
  • 在我执行写入命令并在 localSock.on('data', function(data) { } 中操作该数据之后。我不想在附加处理之前将其发送给客户端完成。

标签: node.js express socket.io


【解决方案1】:

全局套接字对象被引用为io.sockets。因此,要全局广播,只需将数据传递给io.sockets.emit(),它将被发送到所有客户端,而不考虑命名空间。

您发布的代码,假设您的意思是io.sockets.on

io.on('connection', function(client) {
    client.broadcast.send(dataToSend);
});

正在侦听与任何命名空间的任何连接,并在建立连接后向所有客户端广播dataToSend。由于您的主要目标是向所有人发送数据,您只需利用全局命名空间io.sockets,但在您的代码中使用它的方式不起作用。

app.get('/execute', function (req, res) {
  var localSock = net.createConnection("10000","127.0.0.1");

  localSock.setEncoding('utf8');
  localSock.on('connect', function(data) {
    var command = req.query.command;
    localSock.write(command);   
  });
  localSock.on('data', function(data) {
    var dataToSend = data;
    localSock.end();
  });

});

在这部分代码中,您正在正确侦听路径 /execute 上的 GET 请求,但您的套接字逻辑不正确。您在连接时立即写入command,这很好,但您假设data 事件意味着数据流已经结束。由于流具有事件end,您可能希望收集带有data 事件的响应,然后最后对end 上的数据进行处理;

例如,如果服务器发送了字符串This is a string that is being streamed.,而您要使用:

localSock.on('data', function(data) {
  var dataToSend = data;
  localSock.end();
});

您可能只收到This is a stri,然后用end() 过早关闭套接字。相反,你会想要这样做:

var dataToSend = [];

localSock.on('data', function(data) {
  dataToSend.push(data);
});
localSock.on('end', function() {
  dataToSend = dataToSend.join('');
  io.sockets.emit(dataToSend);
});

请注意,在这种情况下,您不需要使用end(),因为删除服务器会发送自己的FIN 数据包。

想问一下你用net.Socket做什么,因为返回的数据是Readable Stream,也就是说,当你监听data事件时,数据可能是完整的片段在触发end 事件之前必须收集的响应。如果您尝试向socket.io 服务器发送消息,那么您可以改用socket.io 自己的客户端socket.io-client

【讨论】:

    【解决方案2】:

    这是来自非常流行的webtutorial 的一些代码。为了使用 Express 3.x,进行了一些更改。

    这里是app.js的代码:

     var express = require('express')
      , http = require('http');
    
    var app = express();
    var server = http.createServer(app);
    var io = require('socket.io').listen(server);
    
    server.listen(8000);
    // routing
    app.get('/', function (req, res) {
      res.sendfile(__dirname + '/index.html');
    });
    
    // usernames which are currently connected to the chat
    var usernames = {};
    
    io.sockets.on('connection', function (socket) {
    
        // when the client emits 'sendchat', this listens and executes
        socket.on('sendchat', function (data) {
            // we tell the client to execute 'updatechat' with 2 parameters
            io.sockets.emit('updatechat', socket.username, data);
        });
    
        // when the client emits 'adduser', this listens and executes
        socket.on('adduser', function(username){
            // we store the username in the socket session for this client
            socket.username = username;
            // add the client's username to the global list
            usernames[username] = username;
            // echo to client they've connected
            socket.emit('updatechat', 'SERVER', 'you have connected');
            // echo globally (all clients) that a person has connected
            socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
            // update the list of users in chat, client-side
            io.sockets.emit('updateusers', usernames);
        });
    
        // when the user disconnects.. perform this
        socket.on('disconnect', function(){
            // remove the username from global usernames list
            delete usernames[socket.username];
            // update list of users in chat, client-side
            io.sockets.emit('updateusers', usernames);
            // echo globally that this client has left
            socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
        });
    });
    

    上面的代码与 webtutorial 中的代码相同,只是 Express 3.x 的一些更改是使用 answer of Riwels 进行的。

    这里是index.html的代码:

     <script src="/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        var socket = io.connect('http://localhost:8000');
    
        // on connection to server, ask for user's name with an anonymous callback
        socket.on('connect', function(){
            // call the server-side function 'adduser' and send one parameter (value of prompt)
            socket.emit('adduser', prompt("What's your name?"));
        });
    
        // listener, whenever the server emits 'updatechat', this updates the chat body
        socket.on('updatechat', function (username, data) {
            $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
        });
    
        // listener, whenever the server emits 'updateusers', this updates the username list
        socket.on('updateusers', function(data) {
            $('#users').empty();
            $.each(data, function(key, value) {
                $('#users').append('<div>' + key + '</div>');
            });
        });
    
        // on load of page
        $(function(){
            // when the client clicks SEND
            $('#datasend').click( function() {
                var message = $('#data').val();
                $('#data').val('');
                // tell server to execute 'sendchat' and send along one parameter
                socket.emit('sendchat', message);
            });
    
            // when the client hits ENTER on their keyboard
            $('#data').keypress(function(e) {
                if(e.which == 13) {
                    $(this).blur();
                    $('#datasend').focus().click();
                }
            });
        });
    
    </script>
    <div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
        <b>USERS</b>
        <div id="users"></div>
    </div>
    <div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
        <div id="conversation"></div>
        <input id="data" style="width:200px;" />
        <input type="button" id="datasend" value="send" />
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 2019-01-06
      • 2011-12-09
      • 2019-03-15
      • 2017-08-03
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      相关资源
      最近更新 更多