Sha256: b581bd1f21dde66731a21a38be9d0a877bfbf3cb99e2b34f93069fe7e340d1f8

Contents?: true

Size: 1.54 KB

Versions: 3

Compression:

Stored size: 1.54 KB

Contents

# # frozen_string_literal: true
require 'faye/websocket'
require 'eventmachine'
require 'json'

module MKIt
  class WebSocketClient
    def initialize(server_url, my_id)
      @server_url = server_url
      @my_id = my_id
      uri = URI(@server_url)
      use_ssl = uri.scheme == 'https'
      @options = use_ssl ? { tls: { :verify_peer => false } } : {}
      @options[:headers] = { 'X-API-KEY' => @my_id }
      url_prefix = use_ssl ? "wss" : "ws"
      @ws_url = "#{url_prefix}://#{uri.host}:#{uri.port}"
      trap("SIGINT") do
        puts "Bye..."
        EventMachine.stop
      end
    end

    def request(request, request_data)
      uri = request[:uri]
      unless request[:params].nil? || request[:params].empty?
        uri = uri + '?' + request[:params].map { |k, v| "#{k}=#{v}" }.join('&')
      end
      uri = ERB.new("#{@ws_url}#{uri}").result_with_hash(request_data)
      
      EM.run {
        ws = Faye::WebSocket::Client.new(uri, nil, @options) 

        ws.on :open do |event|
          # no op
        end

        ws.on :message do |event|
          puts event.data
        end

        ws.on :error do |event|
          p [:error, event.message]
          ws = nil
          return
        end

        ws.on :close do |event|
          ws = nil
          EventMachine.stop
        end

        Thread.new do
          loop do
            input = STDIN.gets.chomp
            if input == 'exit'
              puts "bye..."
              EventMachine.stop
              break
            end
          end
        end
      }
    end
  end
end



Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mkit-0.7.2 lib/mkit/client/websocket_client.rb
mkit-0.7.1 lib/mkit/client/websocket_client.rb
mkit-0.7.0 lib/mkit/client/websocket_client.rb