gpt4 book ai didi

Node.js 网络事件不会触发

转载 作者:IT老高 更新时间:2023-10-28 23:07:56 27 4
gpt4 key购买 nike

我有以下监听连接和数据事件的示例,以将结果回显给监听端口 8888 的其他 telnet 客户端。我的 telnet session 可以正常连接到 locahost,但没有回显输出。我正用头撞砖墙,试图找出问题所在。执行甚至没有达到“连接”事件。

/server.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;
console.log(id);
client.on('connect', function () {
console.log('A new connection was made');
channel.emit('join', id, client);
});
client.on('data', function (data) {
data = data.toString();
channel.emit('broadcast', id, data);
});
});

server.listen(8888);

然后我在命令行中运行

node server.js
telnet 127.0.0.1 8888

最佳答案

当调用 net.createServer 的回调时,这是因为隐含的 connection 事件。所以你的代码应该是这样的:

var server = net.createServer(function (client) {

// when this code is run, the connection has been established

var id = client.remoteAddress + ':' + client.remotePort;
console.log('A new connection was made:', id);

channel.emit('join', id, client);

client.on('data', function(data) {
...
});

client.on('end', function() {
...
});
});

关于Node.js 网络事件不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16903844/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com