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') {|pubsub| ... } ⇒ Object

Yields:

  • (pubsub)


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/simplepubsub.rb', line 85

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

  pubsub = PubSub.new
  yield(pubsub)

  EM.run do

    address = hostname + ':' + port

    ws = WebSocket::EventMachine::Client.connect(:uri => 'ws://' + address)

    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
      (ws.close; EM.stop) if r == :stop
    end

    ws.onclose do
      puts "Disconnected"
    end

    EventMachine.next_tick do
      ws.send pubsub.topic + ': ' + pubsub.message
    end


  end
end