Class: Moonrelay::Cli::ProxyCommand

Inherits:
Clamp::Command
  • Object
show all
Defined in:
lib/moonrelay/cli/proxy_command.rb

Instance Method Summary collapse

Instance Method Details

#executeObject



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
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/moonrelay/cli/proxy_command.rb', line 13

def execute

  downstream = Queue.new
  upstream = Queue.new
  proxy_server = TCPServer.open("0.0.0.0", 2000)

  Thread.new do
    loop do
      c = proxy_server.accept    # Wait for a client to connect
      puts "conn"
      t = Thread.new do
        loop do
          m = downstream.pop
          print m
          c.write m
        end
      end

      while data = c.recv(81920) do
        break if data.empty?
        upstream << data
      end
      puts "disconnect"
      t.kill
    end
  end

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

    ws.on :open do |event|
      puts "ready"
    end

    ws.on :message do |event|
      p [:message, event.data.class, event.data]
      if event.data.is_a? Array
        downstream.push event.data.pack("C*")
      else
        downstream.push event.data
      end
    end

    ws.on :close do |event|
      p [:close, event.code, event.reason]
      ws = nil
    end

    Thread.new do
      loop do
        m = upstream.pop
        # TODO

        puts ""
        puts "----"
        p ["->", m.encoding, m]
        if m.encoding.name == "ASCII-8BIT"
          ws.send m.unpack("C*")
        else
          ws.send m
        end
#                puts m.unpack("C*")
#                ws.send m # .unpack("C*")
#              else
 #               ws.send m
  #            end
      end
    end
  }
end