Class: SimplePubSub::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/simplepubsub.rb

Defined Under Namespace

Classes: PubSub

Class Method Summary collapse

Class Method Details

.connect(hostname, port = '59000', options = {}) {|pubsub| ... } ⇒ Object

Yields:

  • (pubsub)


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
# File 'lib/simplepubsub.rb', line 108

def self.connect(hostname, port='59000', options={})

  pubsub = PubSub.new
  yield(pubsub)

  blk = lambda do |ws, pubsub, em_already_running|

    ws.onopen do
      puts "Connected"
    end

    ws.onmessage do |msg, type|

      a = msg.split(/\s*:\s*/,2)
      topic, message = a
      r = pubsub.proc.call topic, message

      if r == :stop then
        ws.close
        EM.stop if em_already_running == false
      end
    end

    ws.onclose do
      puts "Disconnected"
    end

    EventMachine.next_tick do
      ws.send pubsub.topic + ': ' + pubsub.message
    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)
    blk.call ws, pubsub, em_already_running = true
  rescue

    thread = Thread.new do
      EM.run do 
        ws = c.connect(params)
        blk.call(ws, pubsub, em_already_running = false)
      end
    end
    thread.join
  end

end