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技術的優質平臺!