Sha256: 81bad7da63c01c0c19a33b45422c31593fead36b9fb1289b26dbe7ca51bfb242

Contents?: true

Size: 1.04 KB

Versions: 3

Compression:

Stored size: 1.04 KB

Contents

# frozen_string_literal: true

require 'jellyfish'
require 'websocket_parser'
require 'digest/sha1'

module Jellyfish
  module WebSocket
    ::WebSocket.constants.each do |const|
      const_set(const, ::WebSocket.const_get(const))
    end

    attr_reader :sock, :parser

    def switch_protocol &block
      key = env['HTTP_SEC_WEBSOCKET_KEY']
      accept = [Digest::SHA1.digest("#{key}#{GUID}")].pack('m0')
      @sock = env['rack.hijack'].call
      sock.binmode
      sock.write(<<-HTTP)
HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: #{accept}\r
\r
      HTTP
      @parser = Parser.new
      parser.on_message(&block)
    end

    def ws_start
      while !sock.closed? && IO.select([sock]) do
        ws_read
      end
    end

    def ws_read bytes=8192
      parser << sock.readpartial(bytes)
    rescue EOFError
      sock.close
    end

    def ws_write msg
      sock << Message.new(msg).to_data
    end

    def ws_close
      sock << Message.close.to_data
      sock.close
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jellyfish-1.4.0 lib/jellyfish/websocket.rb
jellyfish-1.3.1 lib/jellyfish/websocket.rb
jellyfish-1.3.0 lib/jellyfish/websocket.rb