Class: Net::WS

Inherits:
HTTP
  • Object
show all
Defined in:
lib/net/ws.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

FIN_FALSE =
0
FIN_TRUE =
1
HEADER_ACCEPT =
"Sec-WebSocket-Accept".freeze
HEADER_CONNECTION =
"Connection".freeze
HEADER_CONNECTION_VALUE =
"Upgrade".freeze
HEADER_EXTENSIONS =
"Sec-WebSocket-Extensions".freeze
HEADER_KEY =
"Sec-WebSocket-Key".freeze
HEADER_SUBPROTOCOL =
"Sec-WebSocket-Protocol".freeze
HEADER_UPGRADE =
"Upgrade".freeze
HEADER_UPGRADE_VALUE =
"websocket".freeze
HEADER_VERSION =
"Sec-WebSocket-Version".freeze
HEADER_VERSION_VALUE =
"13".freeze
LENGTH_IS_16BIT =
126
LENGTH_IS_64BIT =
127
OPCODE_CLOSE =
0x08
OPCODE_PING =
0x09
OPCODE_PONG =
0x0A
OPCODE_TEXT =
0x01
SEC_WEBSOCKET_KEY_LEN =
16
SEC_WEBSOCKET_SUFFIX =
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11".freeze
STATE_CLOSING =
"state_closing".freeze
STATE_CONNECTED =
"state_connected".freeze
STATE_CONNECTING =
"state_connecting".freeze
STATE_FINISHED =
"state_finished".freeze
UNSIGNED_16BIT_MAX =
(2**16) - 1
UNSIGNED_64BIT_MAX =
(2**64) - 1
WEBSOCKET_SCHEME_WS =
"ws".freeze
WEBSOCKET_SCHEME_WSS =
"wss".freeze
WEBSOCKET_SCHEMES =
[WEBSOCKET_SCHEME_WS, WEBSOCKET_SCHEME_WSS].freeze

Instance Method Summary collapse

Constructor Details

#initialize(uri, options = nil) ⇒ WS

Returns a new instance of WS.



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/net/ws.rb', line 51

def initialize(uri, options=nil)
  options ||= {}
  @uri = URI(uri)
  @on_message = options[:on_message]
  @subprotocols = options[:subprotocols].is_a?(Array) ? \
    options[:subprotocols] : \
    [options[:subprocotols]]
  @connection_state = nil

  super(@uri.host, @uri.port)
end

Instance Method Details

#closeObject



83
84
85
86
87
88
# File 'lib/net/ws.rb', line 83

def close
  _send_close
  Timeout.timeout(10) {receive_frame}
rescue Timeout::Error
  finish
end

#open(request_uri = nil) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/net/ws.rb', line 67

def open(request_uri=nil)
  return false if STATE_CONNECTING == @connection_state

  @connection_state = STATE_CONNECTING
  @request_uri = request_uri || @uri.request_uri || "/"

  perform_opening_handshake.tap do |successful|
    @connection_state = STATE_CONNECTED if successful
  end
end

#ping(message = nil) ⇒ Object



78
79
80
81
# File 'lib/net/ws.rb', line 78

def ping(message=nil)
  send_frame(FIN_TRUE, 0, OPCODE_PING, message)
  receive_frame
end

#receive_messageObject



95
96
97
98
# File 'lib/net/ws.rb', line 95

def receive_message
  # TODO fragmentation
  receive_frame
end

#send_text(data) ⇒ Object



90
91
92
93
# File 'lib/net/ws.rb', line 90

def send_text(data)
  # TODO fragmentation
  send_frame(FIN_TRUE, 0, OPCODE_TEXT, data)
end

#to_ioObject



63
64
65
# File 'lib/net/ws.rb', line 63

def to_io
  @socket.io
end