node.js广播功能不一致地广播到所有连接的客户端

时间:2015-05-04 22:05:37

标签: javascript node.js websocket broadcast

我正在尝试为8个tcp客户端创建8个tcp套接字连接。我从websocket客户端接收消息并将每条消息广播到8个tcp客户端。间歇性地,广播不向所有8个TCP客户端广播。无法弄清楚我做错了什么。

    var tcpclients = [];

    var server = new net.createServer(function(socket) {
    socket.pipe(socket);
    tcpclients.push(socket);
    pushed++;
    console.log("pushed=%d", pushed);
    if (pushed == 8) {
        broadcast(UP);
        pushed = 0;
    }

    socket.on('data', function(message) {
        console.log("RECVD: %d image bytes from tcp client", message.length);
        ws.send(message);
    });

    socket.on('end', function(message) {
        console.log("TCP socket closed", arguments);
    });

    socket.on('error', function() {
        console.log("TCP connection error", arguments);
    });
    }).listen(tcpport, host, function() {
       console.log('TCP connection open');
    });
正在从websocket客户端接收

消息,然后使用功能广播(消息)进行广播。

    function broadcast(message) {
    if (tcpclients.length === 0) {
        console.log("no tcp clients active");
        return;
    }
    console.log("broadcast to %d server ranks", tcpclients.length);
    tcpclients.forEach(function(client, index, array) {
        client.write(message);
        console.log("SENT:" + message.length + " message bytes to TCP      client");
    });
    }

0 个答案:

没有答案