Class: Caldecott::Server::WebSocketTunnel

Inherits:
Object
  • Object
show all
Defined in:
lib/caldecott/server/websocket_tunnel.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.run!(opts) ⇒ Object

quack like sinatra



11
12
13
# File 'lib/caldecott/server/websocket_tunnel.rb', line 11

def self.run!(opts)
  WebSocketTunnel.new.start(opts[:port])
end

Instance Method Details

#start(port) ⇒ Object



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
# File 'lib/caldecott/server/websocket_tunnel.rb', line 15

def start(port)
  EM::WebSocket.start(:host => "0.0.0.0", :port => port) do |ws|
    log = SessionLogger::new("server", STDOUT)
    dst_conn = nil

    ws.onopen do
      log.debug "tunnel connected"
      slash, tunnel, host, port = ws.request['Path'].split('/')

      EM::connect(host, port, TcpConnection) do |d|
        dst_conn = d

        dst_conn.onopen do
          log.debug "target connected"
        end

        dst_conn.onreceive do |data|
          log.debug("t <- d #{data.length}")
          ws.send(Base64.encode64(data))
        end

        dst_conn.onclose do
          log.debug "target disconnected"
          ws.close_connection
        end
      end
    end

    ws.onmessage do |msg|
      decoded = Base64.decode64(msg)
      log.debug("t -> d #{decoded.length}")
      dst_conn.send_data(decoded)
    end

    ws.onclose do
      log.debug "tunnel disconnected"
      dst_conn.close_connection_after_writing if dst_conn
    end
  end
end