node中的事件发射器
2024-08-29 12:45:17
在事件环中node通过on和emit进行事件的接收和发射,笔者以简单的窗口聊天小demo来演示一下如何通过事件环来发射和监听事件并执行回掉;
var events=require('events')
var net = require('net')
var channel= new events.EventEmitter();//事件发射器
channel.client={};
channel.subscriptions={}
channel.on("join",function(id,client){
this.client[id]=client;
console.log("--------------------")
var that =this;
this.subscriptions[id]=(senderId,message)=>{
console.log("broadcast")
that.client[id].write(message)
}
channel.on('broadcast',this.subscriptions[id]);//每当进入一个链接就会在事件环中添加一个监听
})
var server = net.createServer(client=>{
console.log("--------------------1")
var id=client.remoteAddress+':'+client.remotePort;
channel.emit("join",id,client)
client.on('connect',()=>{//当用户连上
channel.emit("join",id,client)//第一个参数可以自己定义,只是一个事件的名字,除了error随便用
})
client.on('data',data=>{
data=data.toString();
channel.emit('broadcast',id,data);
})
})
server.listen(8888,()=>{
console.log("I'm listening on port 8888")
})
如上node程序可以监听要来的tcp链接并且通过broadcast广播到所有链接上的tcp客户端
运行上面程序然后可以用telnet 客户端尝试
关于telnet在win上的安装和使用参考
https://blog.csdn.net/msq7487223/article/details/52366148
https://jingyan.baidu.com/article/95c9d20d96ba4aec4f756154.html
最新文章
- EF事务嵌套
- CSS中相对定位与绝对定位
- 树莓派/RaspberryPi 内核编译
- 在后台直接调用sql
- 玉兔IM(康林的博客)
- jdk outMemory内存溢出
- 禁止root登陆sshd/并修改默认端口号
- mybatis 一对一关联 association 返回空值
- 学习笔记DL001:数学符号、深度学习的概念
- Redis学习笔记(1)-安装Oracle VM VirtualBox
- url自动补全index.php
- ZBlog你选择PHP还是ASP?
- linux下如何解除被占用的端口号
- Linux 系统结构详解【转】
- 【转】打包2个10g文件 测试
- 【CSAPP笔记】7. 汇编语言——过程调用
- Foreda8上安装Ant1.9.2
- wusir FTP与HTTP文件传输之TCP Packet解析
- IE8 placeholder不支持的兼容性处理
- Oracle学习-Power Designer、visio 2003、Oracle sql developer、OEM、expdp