Class: SimplePubSub::Server

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

Class Method Summary collapse

Class Method Details

.start(host: '0.0.0.0', port: 59000) ⇒ Object



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/simplepubsub.rb', line 14

def self.start(host: '0.0.0.0', port: 59000)


  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)

        def ws.subscriber?() 
          false
        end
       
        if a.first == 'subscribe to topic' then

          topic = a.last.rstrip.gsub('+','*')\
                                          .gsub('#','*//').gsub('or','|')
          subscribers[topic] ||= []
          subscribers[topic] << ws

          # affix the topic to the subscriber's websocket
          def ws.subscriber_topic=(topic)  @topic = topic     end
          def ws.subscriber_topic()  @topic                   end

          ws.subscriber_topic = topic

        elsif a.length > 1

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

          reg = XMLRegistry.new
          reg[current_topic] = message

          subscribers.each do |topic,conns|

            node = reg.doc.root.xpath topic.gsub(/\S\b/,'\0/text()')

            if node.any? then                  
              conns.each {|x| x.send current_topic + ': ' + message}
            end

          end

          #ws.send msg, :type => type

        end

      end

      ws.onclose do
        puts "Client disconnected"
        if ws.respond_to? :subscriber_topic then
          subscribers[ws.subscriber_topic].delete ws 
        end
      end
    end

  end
end