现在的位置: 首页 > 数据库 > 正文

Redis 的 Pub/Sub 怎样以WebSockets为前端的类EventMachine实现

2020年07月02日 数据库 ⁄ 共 1409字 ⁄ 字号 评论关闭

  EventMachine是一个Ruby的事件驱动网络库,一个以Redis的Pub/Sub机制为后端,以WebSockets为前端的类EventMachine实现。下面学步园小编来讲解下Redis的Pub/Sub怎样以WebSockets为前端的类EventMachine实现?

  Redis的Pub/Sub怎样以WebSockets为前端的类EventMachine实现

  前端代码,创建Socket连接到本地8081端口,当有消息push过来的时候,将消息打印到指定的div里:

  

  

  

  

  

  

  

  

  

  

  

  Redis的Pub/Sub怎样以WebSockets为前端的类EventMachine实现

  后端代码:

  require'redis'

  require'em-websocket'

  SOCKETS=[]

  @redis=Redis.new(:host=>'127.0.0.1',:post=>6379)

  #CreatingathreadfortheEMeventloop

  Thread.newdo

  EventMachine.rundo

  #Createsawebsocketlistener

  EventMachine::WebSocket.start(:host=>'0.0.0.0',:port=>8081)do|ws|

  ws.onopendo

  #WhensomeoneconnectsIwanttoaddthatsockettotheSOCKETSarraythat

  #Iinstantiatedabove

  puts'creatingsocket'

  SOCKETS<   end   ws.onclosedo   #UponthecloseoftheconnectionIremoveitfrommylistofrunningsockets   puts'closingsocket'   SOCKETS.deletews   end   end   end   end   #Creatingathreadfortheredissubscribeblock   Thread.newdo   @redis.subscribe('ws')do|on|   #Whenamessageispublishedto'ws'   on.messagedo|chan,msg|   puts"sendingmessage:#{msg}"   #Sendoutthemessageoneachopensocket   SOCKETS.each{|s|s.sendmsg}   end   end   end   sleep   开启8081端口接受连接,同时连到Redis上订阅ws这个key的消息   当前后端都启动并连接上后,你就可以用如下代码往Redis的ws这个key上写消息,页面上就能看到push过来的消息了:   require'redis'   @redis=Redis.new(:host=>'127.0.0.1',:post=>6379)

  @redis.publish'ws','Somethingwitty'

  以上就是关于“Redis的Pub/Sub怎样以WebSockets为前端的类EventMachine实现”的内容,希望对大家有用。更多资讯请关注学步园。学步园,您学习IT技术的优质平台!

抱歉!评论已关闭.