Sha256: 248a6e263aca14df565f15247279fb7fe181b306767983e989b9e64ebd5b6a8f

Contents?: true

Size: 1.51 KB

Versions: 4

Compression:

Stored size: 1.51 KB

Contents

require 'websocket-eventmachine-server'
module Smash
  module CloudPowers
    module Synapse
      module WebSoc
        module SocServer
          def create_websoc_server(opts = {})
            channel = opts[:channel] || EM::Channel.new
            Thread.new do
              EM.run do
                WebSocket::EventMachine::Server.start(:host => opts[:host], :port => opts[:port]) do |ws|
                  sid = nil

                  open_callback = opts[:on_open] || Proc.new do
                    puts "Client connected"
                    sid = channel.subscribe { |msg| ws.send msg }
                  end
                  ws.onopen &open_callback

                  on_message_callback = opts[:on_message] || Proc.new do |msg, type|
                    @current_websocket_message = msg
                  end
                  ws.onmessage &on_message_callback

                  on_error_callback = opts[:on_error] || Proc.new do |error|
                    puts "Error occured: #{error}"
                  end
                  ws.onerror &on_error_callback

                  on_close_callback = opts[:on_close] || Proc.new do
                    puts "Client disconnected"
                    channel.unsubscribe(sid) unless channel.nil?
                  end
                  ws.onclose &on_close_callback
                end
              end
            end
            channel
          end

          def broadcast_message(channel, msg)
            channel.push msg
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
cloud_powers-1.1.1 lib/cloud_powers/synapse/web_soc/soc_server.rb
cloud_powers-1.1.0 lib/cloud_powers/synapse/web_soc/soc_server.rb
cloud_powers-1.0.1 lib/cloud_powers/synapse/web_soc/soc_server.rb
cloud_powers-1.0.0 lib/cloud_powers/synapse/web_soc/soc_server.rb