class Frame
Represents a single WebSocket frame as defined by RFC 6455.
Definitions
def initialize(finished = true, payload = nil, flags: 0, opcode: self.class::OPCODE, mask: false)
Signature
-
parameter
maskBoolean | String An optional 4-byte string which is used to mask the payload.
Implementation
def initialize(finished = true, payload = nil, flags: 0, opcode: self.class::OPCODE, mask: false)
if mask == true
mask = SecureRandom.bytes(4)
end
@finished = finished
@flags = flags
@opcode = opcode
@mask = mask
@payload = payload
end
def flag?(value)
Check whether the specified RSV flag bit is set on this frame.
Signature
-
parameter
valueInteger The flag bitmask to test (e.g.
RSV1).-
returns
Boolean trueif the flag bit is set.
Implementation
def flag?(value)
@flags & value != 0
end
def <=>(other)
Compare this frame to another frame by their array representation.
Signature
-
parameter
otherFrame The frame to compare against.
-
returns
Integer A comparison result (-1, 0, or 1).
Implementation
def <=> other
to_ary <=> other.to_ary
end
def to_ary
Convert this frame to an array of its fields for comparison or inspection.
Signature
-
returns
Array An array of
[finished, flags, opcode, mask, payload].
Implementation
def to_ary
[@finished, @flags, @opcode, @mask, @payload]
end
def control?
Check whether this is a control frame (opcode has bit 3 set).
Signature
-
returns
Boolean trueif this is a control frame.
Implementation
def control?
@opcode & 0x8 != 0
end
def data?
Signature
-
returns
Boolean if the frame contains data.
Implementation
def data?
false
end
def finished?
Check whether this is the final frame in a message.
Signature
-
returns
Boolean trueif the FIN bit is set.
Implementation
def finished?
@finished == true
end
def continued?
Check whether this frame is a continuation fragment (FIN bit not set).
Signature
-
returns
Boolean trueif the FIN bit is not set.
Implementation
def continued?
@finished == false
end
def length
The byte length of the payload.
Signature
-
returns
Integer | nil
Implementation
def length
@payload&.bytesize
end
def pack(data = "")
Pack the given data into this frame's payload, applying masking if configured.
Signature
-
parameter
dataString The payload data to pack.
-
returns
Frame Returns
self.
Implementation
def pack(data = "")
if data.bytesize.bit_length > 63
raise ProtocolError, "Frame length #{data.bytesize} bigger than allowed maximum!"
end
if @mask
@payload = mask_xor(data, @mask)
else
@payload = data
end
return self
end
def unpack
Unpack the raw payload, removing masking if present.
Signature
-
returns
String The unmasked payload data.
Implementation
def unpack
if @mask and !@payload.empty?
return mask_xor(@payload, @mask)
else
return @payload
end
end
def apply(connection)
Apply this frame to the connection by dispatching it to the appropriate handler.
Signature
-
parameter
connectionConnection The WebSocket connection to receive this frame.
Implementation
def apply(connection)
connection.receive_frame(self)
end