javascript - Node + 远程登录 + OS X

标签 javascript node.js

美好的一天。

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]);
});

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();
    channel.emit('broadcast', id, data);
});
});
server.listen(8888);

当我运行服务器并通过 telnet“广播”连接时,发射不起作用。来自“Node.js 实战”的示例。图书文件中的代码也无法正常工作。请帮忙。可能出了什么问题?我尝试将 id 的生成器更改为 strong inc "i"并省略 ...if (id != senderId)... 但不起作用!!!

最佳答案

net.createServer 的回调函数被调用时,它已经暗示了一个客户端连接。另外,我认为 connect 事件甚至不是由 net.createServer 生成的。

因此,不要在发出“join”之前等待 connect 事件,而是立即发出它:

var server = net.createServer(function(client) {
  var id = client.remoteAddress + ':' + client.remotePort;

  // we got a new client connection:
  channel.emit('join', id, client);

  // wait for incoming data and broadcast it:
  client.on('data', function(data) {
    data = data.toString();
    channel.emit('broadcast', id, data);
  });
});

关于javascript - Node + 远程登录 + OS X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19878076/

相关文章:

javascript - RxJS:使用拖放时如何防止点击元素

javascript - Intl.NumberFormat() 不显示比特币 Ƀ 符号

node.js - 如何写入全局安装的 Node 模块中的文件?

javascript - 如何检查字符串是否以 iFrame 开头?

javascript - 使用 Express/Node.js 和 Angular 处理取消的请求

image - 使用 node.js 跨平台调整图像大小

mysql - Node ,迭代 mysql 行,使用异步库调用另一个 mysql 查询

javascript - 为什么JS是解释型的而不是编译型的?

node.js - Node 命令在 Windows 上的 git bash 终端中不起作用

javascript - Adobe DTM 和具有不同数量元素的数组