Method: Moonrelay::Cli::ExposeCommand#execute

Defined in:
lib/moonrelay/cli/expose_command.rb

#executeObject



12
13
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
# File 'lib/moonrelay/cli/expose_command.rb', line 12

def execute
  s = nil
  downstream = Queue.new
  t = Thread.new do
    loop do
      unless s
        sleep 0.1
        next
      end
      data = s.recv(8192)
      downstream.push data
    end
  end

  EM.run {
    ws = Faye::WebSocket::Client.new("ws://#{server}/#{channel}")

    ws.on :open do |event|
      p [:open]
    end

    ws.on :message do |event|
      s ||= TCPSocket.new host, port

      p [:message, event.data]

      if event.data.is_a? Array
        s.write(event.data.pack("C*"))
      else
        s.write event.data
      end
    end

    Thread.new do
      loop do
        m = downstream.pop
        if m.empty?
          # disconnect TODO
          if s.nil?
            puts "wat"
          else
            t.kill
            s.close
            s = nil
          end
        end

        p ["<-", m]
        ws.send(m.unpack("C*"))
      end
    end
    ws.on :close do |event|
      p [:close, event.code, event.reason]
      ws = nil
    end

  }

end