gpt4 book ai didi

javascript - node.js 代码不广播消息

转载 作者:行者123 更新时间:2023-12-03 10:11:36 25 4
gpt4 key购买 nike

我是node.js的新手,我正在按照书中的代码进行操作。代码如下:

const JOIN = "join";
const BROADCAST = "broadcast";
const CONNECT = "connect";
const DATA = "data";
const LEAVE = "leave";
const CLOSE = "close";

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.\n");
});

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);
});
client.on(CLOSE,function(){
channel.emit(LEAVE,id);
});
});

server.listen(8888);

这应该是一个命令行聊天程序。然而,这不起作用。它不会按预期广播消息。此外,每当有人离开聊天室时,就会出现以下错误:

events.js:195
throw TypeError('listener must be a function');
^
TypeError: listener must be a function
at TypeError (<anonymous>)
at EventEmitter.removeListener (events.js:195:11)
at EventEmitter.net.createServer.id (/home/archenemy/node-workspace/simplechat.js:26:10)
at EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (/home/archenemy/node-workspace/simplechat.js:40:11)
at Socket.EventEmitter.emit (events.js:95:17)
at TCP.close (net.js:466:12)

我该如何纠正这个问题?

最佳答案

在您的事件处理程序中,您在多个地方使用它而不是 channel 。确保“this”实际上指的是 channel 对象。请记住,您在这里处理的是回调,并且“this”并不总是意味着您在涉及回调时所认为的含义。

channel.on(JOIN,function(id,client){
channel.clients[id] = client;
channel.subscriptions[id] = function(senderId,message){
if( id != senderId ){
channel.clients[id].write(message);
}
}
channel.on(BROADCAST,channel.subscriptions[id]);
});

channel.on(LEAVE,function(id){
channel.removeListener(BROADCAST,channel.subscriptions[id]);
channel.emit(BROADCAST,id, id + " has left.\n");
});

关于javascript - node.js 代码不广播消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30085954/

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