Class: Tina4::WebSocketConnection

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, socket) ⇒ WebSocketConnection

Returns a new instance of WebSocketConnection.



94
95
96
97
# File 'lib/tina4/websocket.rb', line 94

def initialize(id, socket)
  @id = id
  @socket = socket
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



92
93
94
# File 'lib/tina4/websocket.rb', line 92

def id
  @id
end

Instance Method Details

#close(code: 1000, reason: "") ⇒ Object



114
115
116
117
118
119
# File 'lib/tina4/websocket.rb', line 114

def close(code: 1000, reason: "")
  payload = [code].pack("n") + reason
  frame = build_frame(0x8, payload)
  @socket.write(frame) rescue nil
  @socket.close rescue nil
end

#read_frameObject



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/tina4/websocket.rb', line 121

def read_frame
  first_byte = @socket.getbyte
  return nil unless first_byte

  opcode = first_byte & 0x0F
  second_byte = @socket.getbyte
  return nil unless second_byte

  masked = (second_byte & 0x80) != 0
  length = second_byte & 0x7F

  if length == 126
    length = @socket.read(2).unpack1("n")
  elsif length == 127
    length = @socket.read(8).unpack1("Q>")
  end

  mask_key = masked ? @socket.read(4).bytes : nil
  data = @socket.read(length) || ""

  if masked && mask_key
    data = data.bytes.each_with_index.map { |b, i| b ^ mask_key[i % 4] }.pack("C*")
  end

  { opcode: opcode, data: data }
rescue IOError, EOFError
  nil
end

#send_pong(data) ⇒ Object



107
108
109
110
111
112
# File 'lib/tina4/websocket.rb', line 107

def send_pong(data)
  frame = build_frame(0xA, data || "")
  @socket.write(frame)
rescue IOError
  # Connection closed
end

#send_text(message) ⇒ Object



99
100
101
102
103
104
105
# File 'lib/tina4/websocket.rb', line 99

def send_text(message)
  data = message.encode("UTF-8")
  frame = build_frame(0x1, data)
  @socket.write(frame)
rescue IOError
  # Connection closed
end