Module: Jellyfish::WebSocket

Defined in:
lib/jellyfish/websocket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#parserObject (readonly)

Returns the value of attribute parser.



13
14
15
# File 'lib/jellyfish/websocket.rb', line 13

def parser
  @parser
end

#sockObject (readonly)

Returns the value of attribute sock.



13
14
15
# File 'lib/jellyfish/websocket.rb', line 13

def sock
  @sock
end

Instance Method Details

#switch_protocol(&block) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/jellyfish/websocket.rb', line 15

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

#ws_closeObject



47
48
49
50
# File 'lib/jellyfish/websocket.rb', line 47

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

#ws_read(bytes = 8192) ⇒ Object



37
38
39
40
41
# File 'lib/jellyfish/websocket.rb', line 37

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

#ws_startObject



31
32
33
34
35
# File 'lib/jellyfish/websocket.rb', line 31

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

#ws_write(msg) ⇒ Object



43
44
45
# File 'lib/jellyfish/websocket.rb', line 43

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