Class: SimplePubSub::Client
- Inherits:
-
Object
- Object
- SimplePubSub::Client
- Defined in:
- lib/simplepubsub.rb
Defined Under Namespace
Classes: PubSub
Class Method Summary collapse
Class Method Details
.connect(hostname, port: '59000', &connect_blk) ⇒ Object
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/simplepubsub.rb', line 107 def self.connect(hostname, port: '59000', &connect_blk) pubsub = PubSub.new connect_blk.call(pubsub) blk = lambda do |ws, pubsub, em_already_running| ws.onopen do puts "Connected" end ws. do |msg, type| a = msg.split(/\s*:\s*/,2) topic, = a EM.defer {pubsub.proc.call topic, } end ws.onclose do puts "Disconnected" # reconnect within a minute seconds = rand(60) seconds.downto(1) do |i| s = "reconnecting in %s seconds" % i; print s sleep 1 print "\b" * s.length end puts self.connect hostname, port: port, &connect_blk end EventMachine.next_tick do ws.send pubsub.topic + ': ' + pubsub. end end address = hostname + ':' + port params = {uri: 'ws://' + address} c = WebSocket::EventMachine::Client begin # attempt to run a websocket assuming the EventMachine is # already running ws = c.connect(params, &connect_blk) blk.call ws, pubsub, em_already_running = true rescue thread = Thread.new do EM.run do ws = c.connect(params, &connect_blk) blk.call(ws, pubsub, em_already_running = false) end end thread.join end end |