Class: SimplePubSub::Server

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

Instance Method Summary collapse

Instance Method Details

#start(options = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/simplepubsub.rb', line 13

def start(options={})

  opt = {host: '0.0.0.0', port: 59000}.merge options
  host, port = opt[:host], opt[:port]

  EM.run do

    subscribers = {}

    WebSocket::EventMachine::Server.start(host: host, port: port) do |ws|

      ws.onopen do
        puts "Client connected"
      end

      ws.onmessage do |msg, type|

        puts "Received message: #{msg}"

        a = msg.split(/\s*:\s*/,2)
       
        if a.first == 'subscribe to topic' then

          topic = a.last
          subscribers[topic] ||= []
          subscribers[topic] << ws 

        elsif a.length > 1

          puts "publish this %s: %s" % a
          topic, message = a

          if subscribers[topic] and subscribers[topic].any? then

            connections = subscribers[topic]
            connections += subscribers['#'] if subscribers['#']
            connections.each {|c| c.send message }
          end

        end

        ws.send msg, :type => type
      end

      ws.onclose do
        puts "Client disconnected"
      end
    end

  end
end