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, ws_server: nil, path: "/") ⇒ WebSocketConnection

Returns a new instance of WebSocketConnection.



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

def initialize(id, socket, ws_server: nil, path: "/")
  @id = id
  @socket = socket
  @params = {}
  @ws_server = ws_server
  @path = path
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



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

def id
  @id
end

#paramsObject

Returns the value of attribute params.



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

def params
  @params
end

#pathObject

Returns the value of attribute path.



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

def path
  @path
end

Instance Method Details

#broadcast(message, include_self: false) ⇒ Object

Broadcast a message to all other connections on the same path



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

def broadcast(message, include_self: false)
  return unless @ws_server

  @ws_server.connections.each do |cid, conn|
    next if !include_self && cid == @id
    next if conn.path != @path
    conn.send_text(message)
  end
end

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



133
134
135
136
137
138
# File 'lib/tina4/websocket.rb', line 133

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



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/tina4/websocket.rb', line 140

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(message) ⇒ Object Also known as: send_text



116
117
118
119
120
121
122
# File 'lib/tina4/websocket.rb', line 116

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

#send_pong(data) ⇒ Object



126
127
128
129
130
131
# File 'lib/tina4/websocket.rb', line 126

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