Sha256: c5fdcbff898c2f669f84dc2a0a511d077c39ab29409029b7678d65a146d5354a

Contents?: true

Size: 1.24 KB

Versions: 9

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

export :handler

require 'digest/sha1'
require 'websocket'

# Websocket connection
class WebsocketConnection
  def initialize(client, headers)
    @client = client
    @headers = headers
    setup(headers)
  end

  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

  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

  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

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

def handler(&block)
  proc { |client, header|
    block.(WebsocketConnection.new(client, header))
  }
end

Version data entries

9 entries across 9 versions & 2 rubygems

Version Path
polyphony-http-0.28 lib/polyphony/websocket.rb
polyphony-http-0.27 lib/polyphony/websocket.rb
polyphony-http-0.26 lib/polyphony/websocket.rb
polyphony-http-0.25 lib/polyphony/websocket.rb
polyphony-http-0.24 lib/polyphony/websocket.rb
polyphony-0.23 lib/polyphony/websocket.rb
polyphony-0.22 lib/polyphony/websocket.rb
polyphony-0.21 lib/polyphony/websocket.rb
polyphony-0.20 lib/polyphony/websocket.rb