在事件环中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

最新文章

  1. EF事务嵌套
  2. CSS中相对定位与绝对定位
  3. 树莓派/RaspberryPi 内核编译
  4. 在后台直接调用sql
  5. 玉兔IM(康林的博客)
  6. jdk outMemory内存溢出
  7. 禁止root登陆sshd/并修改默认端口号
  8. mybatis 一对一关联 association 返回空值
  9. 学习笔记DL001:数学符号、深度学习的概念
  10. Redis学习笔记(1)-安装Oracle VM VirtualBox
  11. url自动补全index.php
  12. ZBlog你选择PHP还是ASP?
  13. linux下如何解除被占用的端口号
  14. Linux 系统结构详解【转】
  15. 【转】打包2个10g文件 测试
  16. 【CSAPP笔记】7. 汇编语言——过程调用
  17. Foreda8上安装Ant1.9.2
  18. wusir FTP与HTTP文件传输之TCP Packet解析
  19. IE8 placeholder不支持的兼容性处理
  20. Oracle学习-Power Designer、visio 2003、Oracle sql developer、OEM、expdp

热门文章

  1. Nginx做流媒体服务Windows版实现直播
  2. 洛谷P2886 [USACO07NOV]牛继电器Cow Relays
  3. Windows安装nvm和node, 以及安装live-server
  4. R语言实战基本方法
  5. sed 命令简介
  6. jS弹出新窗口被拦截的解决方法
  7. 释放jQuery 的$ 的使用权
  8. 对于一个段错误(核心已转储)问题的解答,错误的英文翻译是segment fault(core dumped)
  9. python并发_线程
  10. QT 定时器详解