美好的一天。
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/