搜尋

首頁  >  問答  >  主體

javascript - NodeJs实现简单的广播

用telnet 127.0.0.1 8888链接后无法实现广播

var events = require('events');
var net = require('net');

var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};

channel.on('join', function(id, client) {
    this.clients[id] = client;
    this.subscriptions[id] = function(senderId, message) {
        if (id != senderId) {
            this.clients[id].write(message);
        }
    };
    this.on('broadcast', this.subscriptions[id]);
});

channel.on('leave', function(id) {
    channel.removeListener('broadcast', this.subscriptions[id]);
    channel.emit('broadcast', id, id + " has left the chat.\n");
});

channel.on('shutdown', function() {
    channel.emit('broadcast', '', "Chat has shut down.\n");
    channel.removeAllListeners('broadcast');
});

var server = net.createServer(function(client){
    var id = client.remoteAddress + ':' + client.remotePort;
    client.on('connect', function() {
        channel.emit('join', id, client);
    });
    client.on('data', function(data) {
        data = data.toString();
        if (data == "shutdown\r\n") {
            channel.emit('shutdown');
        }
        channel.emit('broadcast', id, data);
    });
    
    client.on('close', function() {
        channel.emit('leave', id);
    });
    
});

server.listen(8888);
PHP中文网PHP中文网2818 天前296

全部回覆(1)我來回復

  • PHP中文网

    PHP中文网2017-04-10 17:37:37

    用socket.io,https://www.npmjs.com/package/socket.io可以试试么?

    回覆
    0
  • 取消回覆