Module: Smash::CloudPowers::Synapse::WebSocServer

Included in:
Smash::CloudPowers::Synapse
Defined in:
lib/cloud_powers/synapse/websocket/websocserver.rb

Instance Method Summary collapse

Instance Method Details

#create_websoc_server(host, port) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/cloud_powers/synapse/websocket/websocserver.rb', line 7

def create_websoc_server( host, port )
  @channel = EM::Channel.new
  Thread.new do
    EM.run do
      WebSocket::EventMachine::Server.start(:host => host, :port => port) do |ws|
        sid = nil

        ws.onopen do
          puts "Client connected"
          sid = @channel.subscribe { |msg| ws.send msg }
        end

        ws.onmessage do |msg, type|
          puts "Received message: #{msg}"
          @channel.push "<#{sid}>: #{msg}"
        end

        ws.onerror do |error|
          puts "Error occured: #{error}"
        end

        ws.onclose do
          puts "Client disconnected"
          @channel.unsubscribe(sid) unless @channel.nil?
        end
      end
    end
  end
end

#send(msg) ⇒ Object



37
38
39
# File 'lib/cloud_powers/synapse/websocket/websocserver.rb', line 37

def send( msg )
  @channel.push "#{msg}" unless @channel.nil? nil
end