Method: Relay#bind

Defined in:
lib/relay.rb

#bind(ws, remote_ip) ⇒ Object



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
# File 'lib/relay.rb', line 16

def bind(ws, remote_ip)
  @ws = ws
  @sig = "#{ws.signature}.#{signature}"
  @completion = EventMachine::Completion.new
  @closed = false
  @unbind_sent = false
  @unbind_recv = false
  @remote_ip = remote_ip
  @connection_inactivity_timeout = comm_inactivity_timeout
  @log.call "[+] bind."
  @ws.onbinary do |data|
    if @closed
      @log.call "[~] data discard, bound closed.", connerror: error?, bytes: data.bytesize
    else
      send_data(data)
    end
  end
  @ws.onmessage do |msg|
    if msg == "unbind"
      @unbind_recv = true
      if @unbind_sent
        @completion.succeed
      else
        close_connection
      end
    else
      @log.call "[!] unexpected text on websocket.", msg: msg
    end
  end
  @ws.onclose do
    close_connection
    @completion.fail
    close_info = @ws.instance_variable_get(:@handler).instance_variable_get(:@close_info) || {}
    code = close_info[:code]
    reason = close_info[:reason]
    if reason
      reason = reason.empty? ? nil : reason.inspect
    end
    @log.call "[-] websocket is closed.", code: code, reason: reason
  end
  resume
  @completion
end