Class: WebsocketConnection

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

Overview

Websocket connection

Constant Summary collapse

S_WS_GUID =
'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
UPGRADE_RESPONSE =
<<~HTTP.gsub("\n", "\r\n")
  HTTP/1.1 101 Switching Protocols
  Upgrade: websocket
  Connection: Upgrade
  Sec-WebSocket-Accept: %<accept>s

HTTP

Instance Method Summary collapse

Constructor Details

#initialize(client, headers) ⇒ WebsocketConnection

Returns a new instance of WebsocketConnection.



10
11
12
13
14
# File 'lib/polyphony/websocket.rb', line 10

def initialize(client, headers)
  @client = client
  @headers = headers
  setup(headers)
end

Instance Method Details

#recvObject



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/polyphony/websocket.rb', line 34

def recv
  loop do
    data = @client.readpartial(8192)
    break nil unless data

    @reader << data
    if (msg = @reader.next)
      break msg.to_s
    end
  end
end

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



46
47
48
49
50
51
# File 'lib/polyphony/websocket.rb', line 46

def send(data)
  frame = ::WebSocket::Frame::Outgoing::Server.new(
    version: @version, data: data, type: :text
  )
  @client << frame.to_s
end

#setup(headers) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/polyphony/websocket.rb', line 25

def setup(headers)
  key = headers['Sec-WebSocket-Key']
  @version = headers['Sec-WebSocket-Version'].to_i
  accept = Digest::SHA1.base64digest([key, S_WS_GUID].join)
  @client << format(UPGRADE_RESPONSE, accept: accept)

  @reader = ::WebSocket::Frame::Incoming::Server.new(version: @version)
end