Class: DRb::WebSocket::SocketPool

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, ws) ⇒ SocketPool

Returns a new instance of SocketPool.



90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/opal/drb/websocket.rb', line 90

def initialize(uri, ws)
  @uri = uri
  @ws = ws
  @handlers = {}

  ws.onmessage do |event|
    message_data = event.data.to_s
    sender_id = message_data.slice(0, 36)
    message = message_data.slice(36, message_data.length - 36)
    @handlers.delete(sender_id).call(message)
  end
end

Instance Attribute Details

#uriObject (readonly)

Returns the value of attribute uri.



88
89
90
# File 'lib/opal/drb/websocket.rb', line 88

def uri
  @uri
end

#wsObject (readonly)

Returns the value of attribute ws.



88
89
90
# File 'lib/opal/drb/websocket.rb', line 88

def ws
  @ws
end

Class Method Details

.new_connection(uri) ⇒ Object



108
109
110
111
112
113
114
115
116
# File 'lib/opal/drb/websocket.rb', line 108

def self.new_connection(uri)
  ws = ::WebSocket.new(uri)

  ws.onclose do
    @sockets[uri] = new_connection(uri)
  end

  self.new(uri, ws)
end

.open(uri) ⇒ Object



103
104
105
106
# File 'lib/opal/drb/websocket.rb', line 103

def self.open(uri)
  @sockets ||= {}
  @sockets[uri] ||= new_connection(uri)
end

Instance Method Details

#[](uri) ⇒ Object



133
134
135
# File 'lib/opal/drb/websocket.rb', line 133

def [](uri)
  @sockets[uri].ws
end

#send(data, &block) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/opal/drb/websocket.rb', line 118

def send(data, &block)
  sender_id = SecureRandom.uuid
  @handlers[sender_id] = block
  byte_data = sender_id.bytes.each_slice(2).map(&:first)
  byte_data += data.bytes.each_slice(2).map(&:first)

  if @ws.connecting?
    @ws.onopen do
      @ws.send(`new Uint8Array(#{byte_data}).buffer`)
    end
  else
    @ws.send(`new Uint8Array(#{byte_data}).buffer`)
  end
end