Sha256: 38f4045d1b867960de9e6a1f03128c804ece2f1ffecd6842c0729007bd936c31

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

require 'websocket-eventmachine-server'
module Smash
  module CloudPowers
    module Synapse
      module WebSocServer
        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 send(channel, msg)
          channel.push msg
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cloud_powers-0.2.7.20 lib/cloud_powers/synapse/websocket/websocserver.rb