Class: WEBrocket::WebSocket

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

Defined Under Namespace

Classes: InternalError

Constant Summary collapse

OP_CONTINUE =
0x0
OP_TEXT =
0x1
OP_BINARY =
0x2
OP_CLOSE =
0x8
OP_PING =
0x9
OP_PONG =
0xA
CLOSE_OK =
[1000].pack("n")
CLOSE_CLOSED =
[1001].pack("n")
CLOSE_PROTOCOL_ERROR =
[1002].pack("n")
CLOSE_BROKEN_DATA =
[1003].pack("n")
CLOSE_BROKEN_MESSAGE =
[1007].pack("n")
CLOSE_POLICY_ERROR =
[1008].pack("n")
CLOSE_TOO_BIG =
[1009].pack("n")
CLOSE_UNKNOWN_ERROR =
[1011].pack("n")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sock, listener, subprotocol) ⇒ WebSocket

Returns a new instance of WebSocket.



23
24
25
26
27
28
29
# File 'lib/webrocket/websocket.rb', line 23

def initialize(sock, listener, subprotocol)
  @sock = sock
  @listener = listener
  @subprotocol = subprotocol
  @type = nil
  @reason = nil
end

Instance Attribute Details

#subprotocolObject (readonly)

Returns the value of attribute subprotocol.



31
32
33
# File 'lib/webrocket/websocket.rb', line 31

def subprotocol
  @subprotocol
end

Instance Method Details

#on_shutdownObject



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

def on_shutdown
  send_close_frame unless @sock.closed?
  @listener.on_shutdown if @listener.respond_to?(:on_shutdown)
end

#send(data, type = :text) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/webrocket/websocket.rb', line 49

def send(data, type = :text)
  nil until IO.select([], [@sock])
  case type
  when :text
    op = OP_TEXT
  when :binary
    op = OP_BINARY
  else
    raise InternalError, "unknown type: #{type}"
  end
  send_frame(op, data)
end

#startObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/webrocket/websocket.rb', line 33

def start
  @listener.on_open(self) if @listener.respond_to?(:on_open)
  begin
    while true
      r = IO.select([@sock])
      recv_frame if r
    end
  rescue IOError
    @reason ||= CLOSE_CLOSED
  ensure
    @reason ||= CLOSE_UNKNOWN_ERROR
    send_close_frame(@reason) unless @sock.closed?
    @listener.on_close(self) if @listener.respond_to?(:on_close)
  end
end