Class: Tipi::Websocket

Inherits:
Object
  • Object
show all
Defined in:
lib/tipi/websocket.rb

Overview

Websocket connection

Constant Summary collapse

OutgoingFrame =
::WebSocket::Frame::Outgoing::Server

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conn, headers) ⇒ Websocket

Returns a new instance of Websocket.



17
18
19
20
21
22
# File 'lib/tipi/websocket.rb', line 17

def initialize(conn, headers)
  @conn = conn
  @headers = headers
  @version = headers['sec-websocket-version'].to_i
  @reader = ::WebSocket::Frame::Incoming::Server.new(version: @version)
end

Class Method Details

.handler(&block) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/tipi/websocket.rb', line 9

def self.handler(&block)
  proc do |adapter, headers|
    req = Qeweney::Request.new(headers, adapter)
    websocket = req.upgrade_to_websocket
    block.(websocket)
  end
end

Instance Method Details

#closeObject



62
63
64
# File 'lib/tipi/websocket.rb', line 62

def close
  @conn.close
end

#recvObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/tipi/websocket.rb', line 24

def recv
  if (msg = @reader.next)
    return msg.to_s
  end

  @conn.recv_loop do |data|
    @reader << data
    if (msg = @reader.next)
      return msg.to_s
    end
  end

  nil
end

#recv_loopObject



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/tipi/websocket.rb', line 39

def recv_loop
  if (msg = @reader.next)
    yield msg.to_s
  end

  @conn.recv_loop do |data|
    @reader << data
    while (msg = @reader.next)
      yield msg.to_s
    end
  end
end

#send(data) ⇒ Object Also known as: <<



54
55
56
57
58
59
# File 'lib/tipi/websocket.rb', line 54

def send(data)
  frame = OutgoingFrame.new(
    version: @version, data: data, type: :text
  )
  @conn << frame.to_s
end